def login(dbsession, user): from autonomie.models.user.login import Login login = Login(login=u"login", user_id=user.id) login.set_password('pwd') dbsession.add(login) dbsession.flush() login.user = user user.login = login return login
def migrate_datas(): from autonomie_base.models.base import DBSESSION session = DBSESSION() from alembic.context import get_bind connection = get_bind() from autonomie.models.user.login import Login op.execute("update groups set editable=0;") op.execute("update groups set `primary`=0;") op.execute( "update groups set `primary`=1 where name IN ('admin', 'contractor', 'manager')" ) op.execute('update accounts set civilite="Monsieur"') for user in connection.execute(user_helper.select()): login = Login( user_id=user.id, login=user.login, ) login.pwd_hash = user.password, login.active = user.active == 'Y' session.add(login) session.flush() op.execute( 'UPDATE user_groups set login_id="%s" where user_id=%s' % ( login.id, user.id ) ) op.drop_column("accounts", "login") op.drop_column("accounts", "password") op.drop_column("accounts", "active") from autonomie.models.user.user import User for userdatas in connection.execute(userdatas_helper.select()): if userdatas.user_id is None: user = User( lastname=userdatas.coordonnees_lastname, firstname=userdatas.coordonnees_firstname, email=userdatas.coordonnees_email1, civilite=userdatas.coordonnees_civilite or 'Monsieur', ) session.add(user) session.flush() connection.execute( userdatas_helper.update().where( userdatas_helper.c.id == userdatas.id ).values(user_id=user.id) ) else: user = User.get(userdatas.user_id) user.civilite = userdatas.coordonnees_civilite or 'Monsieur' session.merge(user) session.flush() op.execute('update accounts set civilite="Monsieur" where civilite is NULL')
def test_auth(dbsession): """ Test user authentication """ a = Login(login="******") a.set_password('pwd') assert a.auth("pwd") is True strange = "#;\'\\\" $25; é ö ô è à ù" a.set_password(strange) assert not a.auth("pwd") assert a.auth(strange) is True a.active = False assert not a.auth(strange)
def auth_validator(form, value): """ Authentication validator :param obj form: The form object :param dict value: The submitted datas to validate :raises: colander.Invalid on invalid authentication """ logger.debug(u" * Authenticating") if current_login_object is None: login = value.get('login') login_object = Login.find_by_login(login) logger.debug(u" + Login {0}".format(login)) else: login_object = current_login_object logger.debug(u" + Login {0}".format(login_object.login)) password = value.get('password') if not login_object or not login_object.auth(password): logger.error(u" - Authentication : Error") message = u"Erreur d'authentification" exc = colander.Invalid(form, message) exc['password'] = message raise exc else: logger.debug(u" + Authentication : OK")
def connect_user(request, form_datas): """ Effectively connect the user :param obj request: The pyramid Request object :pram dict form_datas: Validated form_datas """ login = form_datas['login'] login_id = Login.id_from_login(login) log.info( u" + '{0}' id : {1} has been authenticated".format( login, login_id ) ) # Storing the form_datas in the request object remember(request, login) remember_me = form_datas.get('remember_me', False) if remember_me: log.info(" * The user wants to be remembered") longtimeout = get_longtimeout() request.response.set_cookie( 'remember_me', "ok", max_age=longtimeout, )
def test_submit_success( self, config, get_csrf_request_with_db, user, groups, ): from autonomie.views.user.login import LoginAddView from autonomie.models.user.login import Login config.add_route('/users/{id}', '/users/{id}') req = get_csrf_request_with_db() req.context = user appstruct = { 'pwd_hash': 'password', 'login': '******', 'primary_group': 'contractor', 'groups': ['trainer'], } view = LoginAddView(req) result = view.submit_success(appstruct) new_login = Login.query().filter_by(login='******').one() assert result.code == 302 assert result.location == '/users/{0}'.format(user.id) assert new_login.groups == ['trainer', 'contractor'] assert new_login.auth('password')
def unique_login(node, value): """ Test login unicity against database """ if not Login.unique_login(value, login_id): message = u"Le login '{0}' n'est pas disponible.".format(value) raise colander.Invalid(node, message)
def submit_success(self, appstruct): model = self.schema.objectify(appstruct) model.userdatas_id = self.current_userdatas.id model = self.dbsession.merge(model) self.dbsession.flush() # Update CareerPath with chosen CareerStage's data model.cae_situation_id = model.career_stage.cae_situation_id model.stage_type = model.career_stage.stage_type model = self.dbsession.merge(model) self.dbsession.flush() # Redirect to login or stage's edition if needed dest_route = self.request.current_route_path(_query='') msg = u"L'étape de parcours a bien été ajoutée" if model.career_stage.cae_situation is not None: if model.career_stage.cae_situation.is_integration: login = Login.query().filter( Login.user_id == self.context.userdatas.user_id).first() if login is None: dest_route = self.request.route_path( '/users/{id}/login', id=self.context.userdatas.user_id) msg = u"L'étape de parcours a bien été ajoutée, \ vous devez maintenant créer les identifiants de l'utilisateur" if model.stage_type is not None: if model.stage_type in ("contract", "amendment", "exit"): dest_route = self.request.route_path('career_path', id=model.id, _query='') self.session.flash(msg) return HTTPFound(dest_route)
def test_submit_success_next_step( self, config, get_csrf_request_with_db, user, groups, ): from autonomie.views.user.login import LoginAddView from autonomie.models.user.login import Login config.add_route('/path1/{id}', '/path1/{id}') config.add_route('/path2/{id}', '/path2/{id}') req = get_csrf_request_with_db() req.context = user req.session['user_form'] = { 'callback_urls': ['/path1/{id}', '/path2/{id}'] } appstruct = {'pwd_hash': 'password', 'login': '******'} view = LoginAddView(req) result = view.submit_success(appstruct) new_login = Login.query().filter_by(login='******').one() assert result.code == 302 assert result.location == '/path2/{0}'.format(user.id) assert req.session['user_form']['callback_urls'] == ['/path1/{id}'] assert new_login.auth('password')
def unique_login(node, value): """ Test login unicity against database """ if not Login.unique_login(value, login_id): message = u"Le login '{0}' n'est pas disponible.".format( value) raise colander.Invalid(node, message)
def test_delete(self, config, user, groups, login, get_csrf_request_with_db): from autonomie.views.user.login import LoginDeleteView from autonomie.models.user.login import Login config.add_route('/users/{id}', '/users/{id}') req = get_csrf_request_with_db() req.context = login login_id = login.id view = LoginDeleteView(req) result = view() assert result.code == 302 assert result.location == '/users/{0}'.format(user.id) req.dbsession.flush() assert Login.get(login_id) is None
def submit_success(self, appstruct): model = self.schema.objectify(appstruct) model.userdatas_id = self.current_userdatas.id model = self.dbsession.merge(model) self.dbsession.flush() self.session.flash(u"L'étape de parcours a bien été enregistrée") dest = u"userdatas/career_path" # Redirect to login management if new CAE situation is integration and no active login if self.context.cae_situation is not None: if self.context.cae_situation.is_integration: login = Login.query().filter( Login.user_id == self.context.userdatas.user_id).first() if login is None: dest = u"login" return HTTPFound( self.request.route_path('/users/{id}/%s' % dest, id=self.context.userdatas_id))
def connect_user(request, form_datas): """ Effectively connect the user :param obj request: The pyramid Request object :pram dict form_datas: Validated form_datas """ login = form_datas['login'] login_id = Login.id_from_login(login) log.info(u" + '{0}' id : {1} has been authenticated".format( login, login_id)) # Storing the form_datas in the request object remember(request, login) remember_me = form_datas.get('remember_me', False) if remember_me: log.info(" * The user wants to be remembered") longtimeout = get_longtimeout() request.response.set_cookie( 'remember_me', "ok", max_age=longtimeout, )
def submit_success(self, appstruct): model = self.schema.objectify(appstruct) model.userdatas_id = self.current_userdatas.id model = self.dbsession.merge(model) self.dbsession.flush() self.session.flash(u"L'étape de parcours a bien été enregistrée") dest = u"userdatas/career_path" # Redirect to login management if new CAE situation is integration and # no active login if self.context.cae_situation is not None: if self.context.cae_situation.is_integration: login = Login.query().filter( Login.user_id == self.context.userdatas.user_id ).first() if login is None: dest = u"login" return HTTPFound( self.request.route_path( '/users/{id}/%s' % dest, id=self.context.userdatas.user_id ) )
def submit_success(self, appstruct): model = self.schema.objectify(appstruct) model.userdatas_id = self.current_userdatas.id model = self.dbsession.merge(model) self.dbsession.flush() # Update CareerPath with chosen CareerStage's data model.cae_situation_id = model.career_stage.cae_situation_id model.stage_type = model.career_stage.stage_type model = self.dbsession.merge(model) self.dbsession.flush() # Redirect to login or stage's edition if needed dest_route = self.request.current_route_path(_query='') msg = u"L'étape de parcours a bien été ajoutée" if model.career_stage.cae_situation is not None: if model.career_stage.cae_situation.is_integration: login = Login.query().filter( Login.user_id == self.context.userdatas.user_id ).first() if login is None: dest_route = self.request.route_path( '/users/{id}/login', id=self.context.userdatas.user_id ) msg = u"L'étape de parcours a bien été ajoutée, \ vous devez maintenant créer les identifiants de l'utilisateur" if model.stage_type is not None: if model.stage_type in ("contract", "amendment", "exit"): dest_route = self.request.route_path( 'career_path', id=model.id, _query='' ) self.session.flash(msg) return HTTPFound(dest_route)
def test_unique_user_id(dbsession, login): assert Login.unique_user_id(login.user_id) == False assert Login.unique_user_id("other login") == True assert Login.unique_login(1, login.id) == True
def test_id_from_login(dbsession, login): assert Login.id_from_login(login.login) == login.id with pytest.raises(Exception): Login.id_from_login("wrong login")
def test_unique_login(dbsession, login): assert Login.unique_login(login.login) == False assert Login.unique_login("test2") == True assert Login.unique_login(login.login, login.id) == True
def test_edit_schema_login_context( dbsession, pyramid_request, login, user, groups ): import colander from autonomie.forms.user.login import get_add_edit_schema from autonomie.models.user.login import Login from autonomie.models.user.user import User user2 = User(email='*****@*****.**', lastname='lastname2', firstname='firstname2') dbsession.add(user2) dbsession.flush() item = Login(user_id=user2.id, login="******") item.set_password('pwd2') dbsession.add(item) dbsession.flush() pyramid_request.context = item schema = get_add_edit_schema(edit=True) schema = schema.bind(request=pyramid_request) result = schema.deserialize( { 'login': '******', 'pwd_hash': '', 'primary_group': "manager", 'groups': ['trainer'], 'user_id': user2.id, } ) assert 'pwd_hash' not in result result = schema.deserialize( { 'login': '******', 'pwd_hash': 'notpwd2', 'primary_group': "manager", 'groups': ['trainer'], 'user_id': user2.id, } ) assert 'pwd_hash' in result # Login already used with pytest.raises(colander.Invalid): schema.deserialize( { 'login': '******', 'pwd_hash': '', 'primary_group': "manager", 'groups': ['trainer'], 'user_id': user2.id, } ) # User already linked to Login class with pytest.raises(colander.Invalid): schema.deserialize( { 'login': '******', 'pwd_hash': 'ooo', 'primary_group': "manager", 'groups': ['trainer'], 'user_id': user.id } ) # wrong primary group with pytest.raises(colander.Invalid): schema.deserialize( { 'login': '******', 'pwd_hash': 'ooo', "primary_group": "falseone", 'groups': ['trainer'], 'user_id': user2.id, } ) # wrong group with pytest.raises(colander.Invalid): schema.deserialize( { 'login': '******', 'pwd_hash': 'ooo', "primary_group": "contractor", 'user_id': user2.id, "groups": ["falseone"], } )
def test_find_by_login(dbsession, login): assert Login.find_by_login(login.login).id == login.id
def unique_user_id(node, value): if not Login.unique_user_id(value, login_id): message = u"Ce compte possède déjà des identifiants.".format( value ) raise colander.Invalid(node, message)
def test_edit_schema_login_context(dbsession, pyramid_request, login, user, groups): import colander from autonomie.forms.user.login import get_add_edit_schema from autonomie.models.user.login import Login from autonomie.models.user.user import User user2 = User(email='*****@*****.**', lastname='lastname2', firstname='firstname2') dbsession.add(user2) dbsession.flush() item = Login(user_id=user2.id, login="******") item.set_password('pwd2') dbsession.add(item) dbsession.flush() pyramid_request.context = item schema = get_add_edit_schema(edit=True) schema = schema.bind(request=pyramid_request) result = schema.deserialize({ 'login': '******', 'pwd_hash': '', 'primary_group': "manager", 'groups': ['trainer'], 'user_id': user2.id, }) assert 'pwd_hash' not in result result = schema.deserialize({ 'login': '******', 'pwd_hash': 'notpwd2', 'primary_group': "manager", 'groups': ['trainer'], 'user_id': user2.id, }) assert 'pwd_hash' in result # Login already used with pytest.raises(colander.Invalid): schema.deserialize({ 'login': '******', 'pwd_hash': '', 'primary_group': "manager", 'groups': ['trainer'], 'user_id': user2.id, }) # User already linked to Login class with pytest.raises(colander.Invalid): schema.deserialize({ 'login': '******', 'pwd_hash': 'ooo', 'primary_group': "manager", 'groups': ['trainer'], 'user_id': user.id }) # wrong primary group with pytest.raises(colander.Invalid): schema.deserialize({ 'login': '******', 'pwd_hash': 'ooo', "primary_group": "falseone", 'groups': ['trainer'], 'user_id': user2.id, }) # wrong group with pytest.raises(colander.Invalid): schema.deserialize({ 'login': '******', 'pwd_hash': 'ooo', "primary_group": "contractor", 'user_id': user2.id, "groups": ["falseone"], })
def unique_user_id(node, value): if not Login.unique_user_id(value, login_id): message = u"Ce compte possède déjà des identifiants.".format(value) raise colander.Invalid(node, message)