Nextcloud external login for users in another database - autologin

I have a Nextcloud installation, with users stored in an external database, and this works fine with this app : https://apps.nextcloud.com/apps/user_sql
With that in place, I can login on my Nextcloud instance via the login form provided by Nextcloud.
I need to autolog the users when they come from another app.
I've written a PHP script, placed at the root of my Nextcloud installation, and it gets called by other internal apps of my company.
This script receives a userId and a token in the URL. After a successful check (no need to get in the details here), this script should log the user in.
Which API should I call to get the user logged in?
I tried the following, without success:
OC_User::login(...)
OC_User::getUserSession()->login(...)
Is there a way to trigger a valid login, so that I can get the users logged in?
Thank you for your answers, guys!

$user = '';
$pass = '';
$s = \OC::$server->getUserSession();
if (!$s->isLoggedin()) $s->login($user, $pass);
else $s->logout();
Placing this at /index.php and before calling OC::handleRequest() does the trick. It doesn`t work as expected but you could try to continue from here.
PD: Nextcloud Server v14.0.0 Alpha

Related

How to access logged in user data in GAE?

I have a site dashboard on GAE standard node.js environment that uses login: admin option in handlers: element in my app.yaml file. This option makes google login window appear before accessing the site. Is it possible to get email and profile of user logged in?
Updates on Feb 2
Tested on my local server
I added login:required in app.yaml; it's a Python3 App but I did not use users api; I start the app with dev_appserver.py to make sure it uses the app.yaml file in the development environment; When I loaded the home page, it prompted me to sign in with test#example.com
I dumped the header output and it included the following
X-Appengine-User-Email: test#example.com
X-Appengine-User-Id: XXXXX
Original Answer
You can use the 'users' Api and call the function GetCurrentUser()
Example, if your code was in python, you'd have something like
from google.appengine.api import users
# Get information about the currently logged in user
users.GetCurrentUser()
# Extra - if you wanted to confirm this is an admin user
users.IsCurrentUserAdmin()
Since you're not using Python, see if the environment variable for USER_EMAIL exists. The source code for users api has the snippet below (so see if it works for you)
email = os.environ.get('USER_EMAIL', email)
_user_id = os.environ.get('USER_ID', _user_id)

Opening a google drive file using the google drive api while I'm NOT signed in to google drive

This has really been bugging me for some time so any help to confirm or affirm this is much appreciated! This is also the first time I actually post a question despite being developing for a long time :)
So I have a nodejs app integrating with the Google Drive API and I want users to authorize multiple Google Drive accounts and be able to view and open (and in general just interact with) all files from the accounts that they add.
I authorize my app using the highest available scope: https://www.googleapis.com/auth/drive and because I don't want users to have to sign-in again when the access_token runs out so I also include the approval_prompt: "force" and ``access_type: "offline"` when I request my access tokens.
Everything is fine - I authorize nicely, I can delete files, I can open them, I can share them, I can download them. Except for one thing:
If I e.g. authorize horse#gmail.com and then beaver#gmail.com. Then I can still delete, share, download and preview files from both accounts. But I simply cannot open documents from horse#gmail.com in google docs for editing (because beaver#gmail.com is signed in on my local machine). The best I can do is getting to a point where it shows me the document, with the right account logged in in the top right corner of the screen, but asks me to sign-in with a button. When I click the button it just refreshes and give me the same message and the same screen.
What I've tried is:
Simply redirecting the user to the file resources alternateLink from the API
Taking the alternateLink and appending my access_token to it and then redirect the user to it.
(and a ton of other random things I found various places that didn't work).
In both cases I have also tried signing out from all google accounts.
Now I checked a couple of webservices like Jollicloud and Odrive that tries something similar. However, both of them appear to force the user to login to google to access a file.
Is it really true that you can do all kinds of crazy things with the users files like deleting and downloading, but you can't open them in Google Docs own apps?
Not completely sure what kind of code I should add to show you what I've got. But here's some. This is my open action (what happens when the user clicks on a file and wants to open the file in the Google Docs/Sheet/etc.) (the orientdb stuff is because we're using the OrientDB graph database - it just fetches an account where we store the tokens). The link is the link property of the file (see below):
open: function(req,res,next){
var link = req.param("link");
var uid = req.param("uid");
orientdb.select().from('Account').where({uid: uid}).one()
.then(function(account){
var URL = link + "&access_token=" + account.tokens.access_token;
res.redirect(URL);
});
}
Here's an example file document from our database (I've replaced all compromising data with a descriptive
ODocument - Class: File id: #13:20499 v.6
name : Hummer2
service : Gdrive
kind : Google Doc
created : Nov 17, 2014
changed : Nov 17, 2014
users : [MB]
uid : mrb#flowtale.com
childID : <FILE.ID>
exportLinks : {DOCX=https://docs.google.com/feeds/download/documents/export/Export?id=<FILE.ID>&exportFormat=docx, Open Office doc=https://docs.google.com/feeds/download/documents/export/Export?id=<FILE.ID>&exportFormat=odt, Rich text=https://docs.google.com/feeds/download/documents/export/Export?id=<FILE.ID>&exportFormat=rtf, HTML=https://docs.google.com/feeds/download/documents/export/Export?id=<FILE.ID>&exportFormat=html, Plain text=https://docs.google.com/feeds/download/documents/export/Export?id=<FILE.ID>&exportFormat=txt, PDF=https://docs.google.com/feeds/download/documents/export/Export?id=<FILE.ID>&exportFormat=pdf}
usernames : [<ARRAY OF USERNAMES ASSOCIATED WITH THIS FILE>]
in_hasFile : User#11:0{out_hasFile:[size=2237],out_hasAccount:[size=4],username:null,email:h#h.com,password:<SOME ENCRYPTED PASSWORD>} v2244
out_belongsTo : Account#12:3{in_belongsTo:[size=6],type:Gdrive,uid:<SOME UID>,tokens:{access_token=<OUR ACCOUNT ACCESS TOKEN>, token_type=Bearer, refresh_token=<OUR ACCOUNT REFRESH TOKEN>, expiry_date=1416258913290},rootFolderID:<ROOT FOLDER ID>,email:<THE ACCOUNT EMAIL>,filesCached:2,usersCached:2,job:4,in_hasAccount:#11:0} v15
in_folderContains : File#13:20495{out_folderContains:[size=2],name:Testhest,service:Gdrive,kind:folder,created:Oct 12, 2014,changed:Oct 12, 2014,users:[1],link:https://docs.google.com/a/flowtale.com/folderview?id=<FOLDER.ID>&usp=drivesdk,uid:mrb#flowtale.com,childID:<FOLDER.ID>,exportLinks:{},usernames:[1],parents:[1],in_hasFile:#11:0,out_belongsTo:#12:3,in_folderContains:#13:13891} v36
link : https://docs.google.com/a/flowtale.com/document/d/<FILE.ID>/edit?usp=drivesdk
Looking forward to hear if anybody can help me or have experienced this before.
Thanks!
The API will allow you to do several actions in your drive account. I haven't been able to reproduce the behavior you mention with files that I haven't granted permissions to another account.
When you authenticate through the OAuth process, you will grant access to your account only to the application which created the OAuth request. You can not edit the content of a file without manually opening it through GDocs. Therefore, when the browser opens the AlternateUrl, it will require you to login to the account, in order to access the file.

LDAP with gitlab: Undefined method persisted

I'm currently setting up a gitlab server using a LDAP backend.
When I try to login as a user present in the LDAP db, I get the following error:
"Could not authorize you from LDAP because: "Undefined method 'persisted?' for #"
Peeking into the source code (specifically app/controllers/omniauth_callbacks_controller.rb) the villain seems to be:
#user = Gitlab::LDAP::User.find_or_create(oauth)
#user.remember_me = true if #user.persisted?
It is totally correct for him to fail here because there is no method persisted? (neither in lib/gitlab/ldap/user.rb nor lib/gitlab/oauth/user.rb). Changing the second line to
#user.remember_me = false #true if #user.persisted?
doesn't work either since remember_me is an invalid function for ruby.
I really have no clue about ruby, let alone Ruby On Rails, so I stopped digging here.
Since I certainly am not the first person to try using LDAP auth in gitlab I consider this an error on my side. Since authentication seems to work (if I enter a false password for the user gitlab happily tells me so), I don't have any idea where to start looking.
I appreciate any help from you guys,
Best Richard
Edit: My gitlab.yml is here.
Solved the problem myself. The database lookup yielded a nil object due to the user creation failing (whenever a ldap user logs in, gitlab uses the ldap data to fill its own database).
During creation of the user database entry the query got an invalid email entry resulting in a failed insert query. Unfortunately this was very hard to debug.
In case anyone should have this problem, try changing the following code in lib/gitlab/oauth/user.rb:
begin
user.save!
rescue ActiveRecord::RecordInvalid => e
raise_error ("(OAuth) Error #{e.to_s}") # <-- add this line
log.info "(OAuth) Email #{e.record.errors[:email]}. Username #{e.record.errors[:username]}"
return nil, e.record.errors
end
This will - in case gitlab is not able to add your user - print the error message the database backend returned as the usual red error banner when trying to log in. Keep in mind to remove this line when you no longer need it.
I can suggest a patch (tested on Gitlab 7.1.0). This code sets the gitlab_rails['ldap_uid'] as username when a ldap user is connecting for the first time :
in /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/oauth/user.rb (see INCLUDE START and STOP) :
user = model.build_user(opts)
user.skip_confirmation!
# Services like twitter and github does not return email via oauth
# In this case we generate temporary email and force user to fill it later
if user.email.blank?
user.generate_tmp_oauth_email
elsif provider != "ldap"
# Google oauth returns email but dont return nickname
# So we use part of email as username for new user
# For LDAP, username is already set to the user's
# uid/userid/sAMAccountName.
email_username = email.match(/^[^#]*/)[0]
# Strip apostrophes since they are disallowed as part of username
user.username = email_username.gsub("'", "")
else
# INCLUDE START
# if LDAP config "ldap_uid" is set : we pick this attribute to set the username :
if ldap_conf['uid'].present?
user.username = auth.extra.raw_info.send(ldap_conf['uid'])[0]
end
# INCLUDE STOP
end
begin
user.save!
In my case the problem was importing (copying file) fro old gitlab repositories to new one.
Gitlab wasn't able to create clean folder for the new user.
Solution:
remove imported repositories
create new, empty repository by first login with LDAP credentials
read your PRIVATE-TOKEN
start gitlab server on your repository ie. 'git daemon --verbose --export-all'
import data from old gitlab using API:
curl -X POST --header "PRIVATE-TOKEN: xxxxxffxxxyyxxxxzzz" http://testserver07.lq/api/v3/projects"?name=project01&import_url=git://localhost/var/opt/gitlab/git-data/repositories-old/repos/project01.git"
First, check if your email address in Gitlab DB is correct:
# login to Gitlab DB (MySql)
mysql -u gitlab gitlabhq_production -p
# check user email address
select email from users where username like 'foo';
Then remove stored LDAP objects from Gitlab DB for the user:
# clear ldap data
update users set extern_uid = '' where username = 'foo';
On next login Gitlab write a new extern_uid.

login session script in nodejs using express.io

i want to create a login session script in nodejs.It should include username and password which is already stored in a database.if the user enter the id which is not in the database then it should show invalid id else it should redirect to another html page.There are lot of frameworks for nodejs but i haven't got any scripts for login session in nodejs.So please anyone can me help by giving me a full script to do these task.

session variable destroyed

I have an issue with login session. Basically the flow is like this:
user creates account and defines a username;
user logins using url 'http://[username].website.com'
(coded in php & mysql, using session cookie)
My problem is: when trying to directly login from the index page 'www.website.com' I don't manage to get my user logged to his URL http://username.website.com
Let say i have opened url "www.example.com" and created a session variable in this url. Now i want to access that session variable in url "test.example.com". How to do that? any solution welcomed
Note: at the top of every php file i have used the below code but my session variable was destroyed and i can't access the session variable in another page. I have also set session.cookie_domain = ".website.com" on "php.ini" file.
ini_set('session.cookie_domain', '.website.com');
session_name("sessionid"); session_start();
Try to put session_start() at the beginning? Remove all other lines and see what happens. It's difficult to diagnose without seeing the actual code.

Resources