Trac Using Database Authentication - python

Is it possible to use a database for authentication with Trac?
.htpasswd auth is not desired in this install.
Using Trac .11 and MySQL as the database. Trac is currently using the database, but provides no authentication.

Out of the box, Trac doesn't actually do its own authentication, it leaves it up to the web server. So, you've got a wealth of Apache-related options available to you. You could maybe look at something like auth_mysql to let you keep user credentials in a database.
Alternatively, take a look at the AccountManagerPlugin on trac-hacks.org

You can use Account Manager Plugin with SessionStore
The AccountManagerPlugin offers several features for managing user accounts:
allow users to register new accounts
login via an HTML form instead of using HTTP authentication
allow existing users to change their passwords or delete their accounts
send a new password to users who’ve forgotten their password
administration of user accounts

Please refer to http://trac-hacks.org/wiki/AccountManagerPlugin
Do the following on your trac.ini
[components]
; be sure to enable the component
acct_mgr.svnserve.* = enabled
acct_mgr.svnserve.svnservepasswordstore = enabled
; choose one of the hash methods
acct_mgr.pwhash.htdigesthashmethod = enabled
acct_mgr.pwhash.htpasswdhashmethod = enabled
[account-manager]
password_store = SvnServePasswordStore
password_file = /path/to/svn/repos/conf/passwd
; choose one of the hash methods
hash_method = HtDigestHashMethod
hash_method = HtPasswdHashMethod
Now trac will use user in the database

Related

how do I add displayName to my user using Pyrebase

I am using Pyrebase in order to work with Firebase on my project.
I have been able to successfully create a user using email and password.
The user object has a field called displayName. How do I enter a value in this at the time of creation?
From what I can see in the Auth implementation of the repo, it does not provide functionality to set the user's display name.
The underlying REST API that Pyrebase is built on does have a method to set the user's account info (including their display name), so it would be possible to include this in Pyrebase. I recommend filing a feature request on the Github repo.
user=auth.sign_in_with_email_and_password(email,password)
info = auth.get_account_info(user['idToken'])
displayname = info['users'][0]['displayName']
I'm building an api in Flask using firebase authentication, I'm using the libs
firebase_admim and pyrebase.
use firebase admin auth method in this way:
auth.create_user(email=email, password=password, display_name=name)
so you can set the display name when creating users

Django Auth with LDAP and Local Accounts

I currently have Django and LDAP working. However, I want to limit LDAP authentication to only the accounts within the local account DB.
i.e if no local account is present deny access/ldap auth occurring.
From looking at the options from LDAPSearch I'm unable to find a direct option to provide this. Any ideas on how to achieve this?
Limiting based on LDAP OU is not an option based on the LDAP address structure in place.
Thanks,
As felix001 pointed out in the comments, the project documentation describes a flag AUTH_LDAP_NO_NEW_USERS:
Prevent the creation of new users during authentication. Any users not already in the Django user database will not be able to login.
Enabling it in the settings turns the desired behaviour on:
# settings.py
...
AUTH_LDAP_NO_NEW_USERS = True
However, this feature is not contained in the currently released 1.7.0 version, so a backport is necessary. The least invasive impl I can think about is:
# myapp/backend.py
from django_auth_ldap import backend as ldap_backend
# backport for AUTH_LDAP_NO_NEW_USERS setting
ldap_backend.LDAPSettings.defaults.update(NO_NEW_USERS=False)
class MyLDAPBackend(ldap_backend.LDAPBackend):
def get_or_build_user(self, username, ldap_user):
user, built = super().get_or_build_user(username, ldap_user)
if self.settings.NO_NEW_USERS and built: # user was not found in local db and created instead
raise ldap_user.AuthenticationFailed(
f'username {username} does not exist in local DB.'
)
return user, built
Activate AUTH_LDAP_NO_NEW_USERS in settings and use the custom backend instead of the LDAPBackend for now:
# myapp/settings.py
AUTH_LDAP_NO_NEW_USERS = True
AUTHENTICATION_BACKENDS += ('myapp.backend.MyLDAPBackend',)
Dropping the backport is also easy: once the next version of django-auth-ldap is released, the only thing you will need to adapt is the AUTHENTICATION_BACKENDS tuple (and of course, remove the myapp/backend.py module).

How to list available authentication backends for a Django user?

I have a project that uses Python 3.6 and Django 1.11 where I use the built-in User model.
The user objects are all inside the default database (which is postgres), but the project uses a second authentication backend because some users need to be authenticated against a legacy Oracle database.
# settings.py
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend', # new postgres DB
'project_config.auth_backends.OtherBackend', # legacy Oracle DB
]
This works fine so far, but now I have 3 groups of users:
some users can only authenticate in ModelBackend because they are not in the legacy DB (because they are new users).
some users can only authenticate in the legacy DB; they have usr.has_usable_password() == False because they have not set their password in the new postgres DB yet.
some users can authenticate in both backends, maybe even with different passwords in each one; this is because they changed their password in the new system, but by design that change is not transmitted back to the legacy DB (don't shoot me, the only way to change the password in the legacy DB is to do it manually through the user interface).
For auditing purposes, I want to list all users and see which backends each one has available (ignoring the is_active flag for now) to make auditing tasks easier.
My idea was to use a loop similar to this one:
for usr in User.objects.all():
backend_list = []
if usr.has_usable_password():
backend_list.append('ModelBackend')
if ... : # what should I check here ?
backend_list.append('OtherBackend')
print(usr, backend_list)
I don't have the passwords for each user for the legacy database, so is may idea even possible?
I have not found a way, but I am open to suggestions.
In the end, I had to go with the suggestion from #ivissani and query the users table in the legacy Oracle DB:
select * from all_users;
With this information at hand, I could compare it to the users in the postgres DB and work out which users appear only in one or in both.

SPA (Ember) authentication vs backend

I am trying to wrap my head around implementing proper authentication in an SPA with a backend.
I am looking at 2 different frontends:
1. SPA with Ember.js
2. Mobile application
I am trying to design a backend that serves both (either in Rails or in Python, have not decided yet). I want the authentication to take place either via Google or Facebook, i.e. I do not need to maintain separate user registrations but I still need to maintain users as I want to be able to 'merge' authentications from Google and Facebook at the end of the day. I also want the backend to be fully stateless for scalability reasons. Also I would prefer to do as much as possible on the client side to spare the load from the backend.
My questions are as follows:
I will request an authentication token in the SPA or in the mobile app. Should I convert this to an access token on the server side or on the client side? I need to authorize backend requests and I need to do that statelessly. My idea was to do everything on the frontend side and pass along the access token to each and every backend request, to be validated on the server side as well but I am not sure if this is an efficient approach.
I want to be able to merge Google and Facebook authentications, what are the best practices for that? I was planning to maintain an user registry on the server side and check the email addresses coming from the authorized backend requests and merge the users if there is a match in email addresses. What are the best practices and are there any libraries supporting this in Python/Flask or in Ruby or Rails?
Thanks!
I'm not really sure what do you mean by 'stateless'. You obviously need some database to store user's data (otherwise you don't need backend at all). So the database is your state. HTTP protocol is stateless by definition, so you can't really be very stateful by other means than storing data in DB.
I will request an authentication token in the SPA or in the mobile app. Should I convert this to an access token on the server side or on the client side?
If you don't need to use Google/Facebook on behalf of your users (and your wording suggests that you don't), you don't need to convert auth_token to server_token at all.
You just need to call Google/Facebook API with that (Ruby has libraries for both, so it's basically a one line of code) and get social network's user ID and user email.
Then you save that ID+email in your database and give your internal server token (just random string) to your user. You generate that string yourself and give it to the client.
If user logs in from another device (i.e. it gives you auth_token with which you find out that user's email belongs to one of already-registered users), you either return existing internal token, or generate new one and bind it to the existing user (depends on what you prioritize – high security of simplicity of implementation/maintenance).
I want to be able to merge Google and Facebook authentications, what are the best practices for that?
Facebook guarantees that if it gives you user email, then it's ensured that that email belongs to the given user. Google, obviously, does the same. So you just merge them by emails.
You don't need some special libraries for that, as it is simple operation with you code on the language of your choice.
I'd organize all the things in database in the following manner:
Users table
id
email
Authentications table
user_id
email
social_uid # facebook number or google email
social_network # string, 'facebook' or 'google'
device # user agent, e.g. 'android'
ip # last login IP address
token # internal token
When user logs in, Authentication object is created. If there is no user with such email, the user is created. If there is a user, it's bind to the authentication object (both via user_id field).
Notes on access tokens
If you do plan to interact with social network (in other ways than just authenticating user), you should exchange auth_token for server_token. server_token is a 'permanent' (well, kind of) authorization token for accessing APIs of social network, whereas auth_token has a very limited lifespan (and some API calls may be restricted if you didn't obtain server_token).
Still, server_token can expire (or user can recall their access for your application), so you should plan ahead to detect that situation and re-acquire token/authorization if needed.
Key points when building Rails app
In Rails, in order to create tables, you need to write migrations:
gem install rails
rails new my_project
cd my_project
rails generate migration create_users
rails generate migration create_authentications
This will generate project folder structure and two migration files, which you need to fill in:
# db/migrate/xxx_create_users.rb
def change
create_table :users do |t|
t.string :email
end
end
# db/migrate/xxx_create_authentications.rb
def change
create_table :authentications do |t|
t.integer :user_id
t.index :user_id
t.string :social_uid
# etc., all other fields
# ...
end
end
Then you generate 'models' to handle database-related manipulations:
# app/models/user.rb
class User < ActiveRecord::Base
has_many :authentications
end
# app/models/authentication.rb
class Authentication < ActiveRecord::Base
belongs_to :user
before_create :set_token
after_commit :create_user_if_needed
private
def set_token
self.token = SecureRandom.urlsafe_base64(20)
end
def create_user_if_needed
unless self.user.present?
self.user.create(email: self.email)
end
end
end
And write 'controller' to handle request from user with a single method inside of it:
# app/controllers/login_controller.rb
class LoginController < ActionController
# Login via Facebook method
def facebook
token = params.require(:auth_token)
# we will use Koala gem
profile = Koala::Facebook::API.new(token).get_object('me', fields: 'email')
# user is created automatically by model
authentication = Authentication.where(social_network: 'facebook', social_uid: profile['id'], email: profile['email']).first_or_create
authentication.update(...) # set ip and device
render json: {token: authentication.token}
end
# This one you'll have to write yourself as an exercise :)
def google
end
end
Of course, you will need to setup routes for your action:
# config/routes.rb
post "login/:action", controller: 'login'
And add Koala (or whatever else you'll use to manage external APIs for which good Ruby packages already exist) to Gemfile:
# Gemfile
gem 'koala'
Then in your terminal run:
bundle install
rails server
And your app is up and running. Well, you'll need to setup your Facebook and Google applications first, get developer keys, and authorize localhost to accept auth_tokens.
Basically, that's it.

Python Simple Salesforce

I am trying to use simple_salesforce to query salesforce data with Python. I am using my username and password, which I am 100% sure is correct. I got the org ID from logging into Salesforce and looking at my company profile. It's only a 15-digit ID. I am specifically using an orgID to avoid using a security token as I don't know what it is. What am I doing wrong?
Code:
from simple_salesforce import Salesforce
sf = Salesforce(instance_url='https://na1.salesforce.com', session_id='')
sf = Salesforce(password='password', username='email', organizationId='15 digit org id')
Output:
File "C:\Python27\lib\site-packages\simple_salesforce\api.py", line 100, in __init__
proxies=self.proxies)
File "C:\Python27\lib\site-packages\simple_salesforce\login.py", line 124, in SalesforceLogin
code=except_code, message=except_msg))
simple_salesforce.login.SalesforceAuthenticationFailed: INVALID_LOGIN: Invalid username, password, security token; or user locked out.
I wrote most of simple-salesforce (although not the organizationId part, as I don't have an IP-whitelisted account to test against)
The standard/vanilla/regular/99% of users should use version is the simple username, password, security_token method.
So something like this
from simple_salesforce import Salesforce
sf = Salesforce(username='nick#nickcatalano.com', password='nickspassword', security_token='tokenemailedtonick')
By far the most confusing part is the security_token part (and was the part I got snagged with.) It turns out the Security Token is emailed to you after a successful password reset. So if you go into your salesforce account and reset your password, I believe you'll end up with an email with the subject salesforce.com security token confirmation which will contain a Security Token in the email. That's your security_token.
To be honest, the security_token kwarg is more a convenience than anything. In the normal email/password/token flow that most users rely on what is actually being sent is email as the login and {password}{security_token} as the password. I believe you could concat that yourself and just pass in a email and password kwarg if you want, but I figured forcing people to concat the password and token themselves would get go against the simple part of simple-salesforce
There is a way to log in with simple-salesforce with only a username and password. No security token required:
from simple_salesforce import Salesforce, SalesforceLogin
session_id, instance = SalesforceLogin(username='<user>', password='<pass>')
sf = Salesforce(instance=instance, session_id=session_id)
# Logged in! Now perform API actions, SOQL queries, etc.
sf.query_all('<soql>')
Explanation
All examples using simple-salesforce begin with a call to the Salesforce constructor to log in. This constructor accepts either an existing session ID, or authentication credentials to log in and make a new session. When logging in, it calls the lower-level SalesforceLogin function to do the real work, but interestingly SalesforceLogin does not enforce the same constraints on its arguments—it issues the correct SOAP call to log in with just a username and password, without requiring a token or organization ID.
Using this trick, we call SalesforceLogin directly, obtain the new session ID, then pass it directly into the Salesforce constructor. From that point on, we are able to make authenticated API requests.
Note
The version of simple-salesforce on PyPI (i.e. pip install simple-salesforce) is very outdated with the simple-salesforce GitHub repository. The latest version supports additional login parameters like domain for login with custom domains. To get the latest version, use
pip install --upgrade https://github.com/simple-salesforce/simple-salesforce/archive/master.zip
(Pip-installing from zip is faster than using git+ssh:// or git+https://, as noted in this answer.)
Edit
How will resetting my password show me what the token is?
It just will. If user has ever before requested the security token (which is sent to you via email - so you need to have access to the email address associated with your user) - every subsequent password reset will result with new token being generated and emailed to you. On top of that, once you're logged in to the system (to the web version, not via API) you will have an option to reset your token (and again, this will send you an email).
It's like you haven't read or tried anything we have written!
Looking for an answer drawing from credible and/or official sources.
https://help.salesforce.com/htviewhelpdoc?id=user_security_token.htm
https://help.salesforce.com/HTViewSolution?id=000004502
https://help.salesforce.com/HTViewSolution?id=000003783
And from the library's documentation:
https://github.com/neworganizing/simple-salesforce
To login using IP-whitelist Organization ID method, simply use your
Salesforce username, password and organizationId
This. If your IP address is whitelisted - you don't need the token. If it isn't - you NEED to generate the token. Period.
Original answer
I'm not familiar with that Python library but... Go to Salesforce -> Setup -> My personal infromation and check login history. if it contains stuff like "failed: security token required" then you're screwed and you will have to use the security token.
I'm not aware of any bypass that uses org id (I've connected via API from PHP, Java, C#... so I'd be very surprised if that Python library had some magical way to bypass it. You probably are used to passing a session id that assumes you're already authenticated and have a valid session.
Another option would be to check your IP and add it to trusted IP ranges (it's an option in the setup). It's useful when for example whole office has same static IP; less useful if you're working from home.
If that's also a no-go - you might want to look for libraries that use OAuth2 instead of regular SOAP API to authenticate.
Although this is kinda late, somebody searching for this very same issue may be helped as to what I did.
I struggled by adding the company ID as well, but the problem here is, unless you're a self-service user, the company ID can be blank.
sf = Salesforce(password='password', username='email', organizationId='')
As other users mentioned, make sure you're using IP-White listing or it will not work.
A security token is an automatically generated key that you must add to the end of your password in order to log into Salesforce from an untrusted network. For example, if your password is mypassword, and your security token is XXXXXXXXXX, then you must enter mypasswordXXXXXXXXXX to log in. Security tokens are required whether you log in via the API or a desktop client such as Connect for Outlook, Connect Offline, Connect for Office, Connect for Lotus Notes, or the Data Loader.
To reset your security token:
At the top of any Salesforce page, click the down arrow next to your name. From the menu under your name, select Setup or My Settings—whichever one appears.
From the left pane, select one of the following:
If you clicked Setup, select My Personal Information | Reset My Security Token.
If you clicked My Settings, select Personal | Reset My Security Token.
Click the Reset Security Token button. The new security token is sent via email to the email address on your Salesforce user record.
If you ip is whitelisted / trusted and you still get invalid login not using the token, You MUST include the security_token='' in the connection string for it to work.
sf = Salesforce(username='USERNAME', password='PASSWORD', security_token='')
A security token is required to login.
Whenever your password is reset, your security token is also reset.
If you do not have a token and cannot reset it.
Try changing your password.
Thanks.
I was able to test that this was working with my security token against a developer org with no issues. This was all done as a standard user with no administrator privileges. Using the OrgId just failed out.
By resetting my password I received a new security token.
username = login for your instance.
password = your password
The code below should get you logged in.
from simple_salesforce import Salesforce
sf = Salesforce(username='username',password='password', security_token='whatever came in reset password')

Categories

Resources