async def create_user_profile(session: AsyncSession, display_name: str, name: str, password: str, role: UserRole, email_address: str = None, phone_number: str = None) -> UUID: if email_address is None and phone_number is None: raise ValueError("one of email address or phone number is required") r = await session.execute(user_profile.insert().values( name=name, display_name=display_name, role=role).returning(user_profile.c.user_profile_id)) profile_id = r.scalar() await session.execute(user_auth.insert().values(user_profile_id=profile_id, password_crypt=f.crypt( password, f.gen_salt('bf', 8)))) if email_address is not None: await add_contact_method(profile_id, email_address=email_address).execute(session) if phone_number is not None: await add_contact_method(profile_id, phone_number=phone_number).execute(session) return profile_id
def setUser(): data = request.get_json() user = User.find(get_jwt_identity()) if not user: return { 'status': 'error', 'message': 'Usuário Inexistente!' }, status.HTTP_400_BAD_REQUEST password = data.get('password', None) newpassword = data.get('newpassword', None) user = User.authenticate(user.email, password) if not user or not newpassword: return { 'status': 'error', 'message': 'Usuário Inexistente!' }, status.HTTP_400_BAD_REQUEST update = {'password': func.crypt(newpassword, func.gen_salt('bf', 8))} db.session.query(User)\ .filter(User.id == user.id)\ .update(update, synchronize_session='fetch') return tryCommit(db, user.id)
def login(self, username, password): with Session() as session: user = session.query(User).filter(User.username == username.lower(), User.password == func.crypt(password, User.password)).first() if user: return True return False
def resetPassword(): data = request.get_json() reset_token = data.get('reset_token', None) newpassword = data.get('newpassword', None) if not reset_token or not newpassword: return { 'status': 'error', 'message': 'Token Inexistente!' }, status.HTTP_400_BAD_REQUEST user_id = decode_token(reset_token)['identity'] user = User.find(user_id) if not user: return { 'status': 'error', 'message': 'Usuário Inexistente!' }, status.HTTP_400_BAD_REQUEST update = {'password': func.crypt(newpassword, func.gen_salt('bf', 8))} db.session.query(User)\ .filter(User.id == user.id)\ .update(update, synchronize_session='fetch') return tryCommit(db, user.id)
def password(self, value): """assign the value of 'password', using a UOW-evaluated SQL function. See http://www.sqlalchemy.org/docs/orm/session.html#embedding-sql-insert-update-expressions-into-a-flush for a description of SQL expression assignment. """ self.password_hashed = func.crypt(value, func.gen_salt('bf'))
def bind_expression(self, bindvalue): """Apply a SQL expression to an incoming cleartext value being rendered as a bound parameter. For this example, this handler is intended only for the INSERT and UPDATE statements. Comparison operations within a SELECT are handled below by the Comparator. """ return func.crypt(bindvalue, func.gen_salt('bf', 8))
def add_user(self, username, password, email, is_admin): with Session() as session: user = session.query(User).filter(User.username == username.lower()).first() if user: raise Exception("User already exists") user = User(username=username.lower(), password=func.crypt(password, func.gen_salt('bf', 8)), email=email, is_admin=is_admin) session.add(user) session.commit()
def put(self, *args, **kwargs): """Modifies user in the system input_json = { 'name': 'Max', 'login': '******', 'password': '******', 'email': '*****@*****.**', 'gender': 0 }""" self.validate_url_params(kwargs) # incoming data check scheme validate = Schema({ Optional('name'): All(Length(min=2, max=32, msg='`name` length is not enough')), Optional('password'): All(Length(min=6, max=32, msg='`password` length is not enough')), Optional('email'): All(Email(msg='`email` did not pass validation')), Optional('gender'): All(In([0, 1], msg='`gender` have to be defined correctly')) }) data = json_decode(self.request.body) validate(data) if data.get('email'): raise M2Error('You are not allowed to change `login`', True) if 'id' in kwargs.keys(): # edit info by user id user = User.load_by_pk(kwargs['id']) if not user: raise M2Error( 'User [%s] with access token [%s] could not be found in DB' % (kwargs['id'], kwargs['access_token'])) else: # edit self info user = User.load_by_pk(self.current_user['id']) if not user: raise M2Error( 'User [%s] with access token [%s] could not be found in DB' % (self.current_user['id'], self.current_user['access_token'])) if 'password' in data.keys(): password = data.pop('password') data['password'] = func.crypt( password, func.gen_salt('bf', options.gen_salt)) user.set(**data) user.save() self.write_json(code=http_statuses['CREATED']['code'], msg=http_statuses['CREATED']['msg'])
def __eq__(self, other): """Compare the local password column to an incoming cleartext password. This handler is invoked when a PasswordType column is used in conjunction with the == operator in a SQL expression, replacing the usage of the "bind_expression()" handler. """ # we coerce our own "expression" down to String, # so that invoking == doesn't cause an endless loop # back into __eq__() here local_pw = type_coerce(self.expr, String) return local_pw == func.crypt(other, local_pw)
def edit_user(self, user_id, password, email, is_admin): with Session() as session: user = session.query(User).filter_by(id=user_id).first() if not user: return False if user.username == "admin": return False user.is_admin = is_admin user.email = email if password: user.password = func.crypt(password, func.gen_salt('bf', 8)) session.commit() # TODO : change to a multicast group # await app.websocket_broadcast( # { # "event": Event.changed.value, # "subject": Subject.user.value, # "changed": {"id": user_id, "is_admin": user.is_admin}, # } # ) return True
def add_user(self, user, password): with Session() as session: user = User(username=user, password=func.crypt(password, func.gen_salt('bf', 8))) session.add(user) session.commit()
def password(self, value): self.hashed_password = func.crypt(value, func.gen_salt('bf'))
def __eq__(self, other): return self.password_hashed == \ func.crypt(other, self.password_hashed)
def __eq__(self, other): return self.__clause_element__() == \ func.crypt(other, self.__clause_element__())
async def authenticate_user(session: AsyncSession, user_profile_id: UUID, password: str) -> bool: q = select(user_auth.c.password_crypt == f.crypt(password, user_auth.c.password_crypt)).\ where(user_auth.c.user_profile_id == user_profile_id) rs = await session.execute(q) return rs.scalar()
def __eq__(self, other): return self.expression == func.crypt(other, self.expression)
def __eq__(self, other): crypted_password = type_coerce(self.expr, String) return crypted_password == func.crypt(other, crypted_password)
def authenticate(email, password): return User.query.filter_by(email=email, password=func.crypt(password, User.password), active=True).first()
def bind_expression(self, value): return func.crypt(value, func.gen_salt('bf'))
def createUser(idUser=None): data = request.get_json() user = User.query.get(get_jwt_identity()) if not user: return { 'status': 'error', 'message': 'Usuário Inexistente!', 'code': 'errors.invalidUser' }, status.HTTP_400_BAD_REQUEST dbSession.setSchema(user.schema) roles = user.config[ 'roles'] if user.config and 'roles' in user.config else [] if ('userAdmin' not in roles): return { 'status': 'error', 'message': 'Usuário não autorizado', 'code': 'errors.unauthorizedUser' }, status.HTTP_401_UNAUTHORIZED if not idUser: userEmail = data.get('email', None) userName = data.get('name', None) emailExists = User.findByEmail(userEmail) != None if emailExists: return { 'status': 'error', 'message': 'Já existe um usuário com este email!', 'code': 'errors.emailExists' }, status.HTTP_400_BAD_REQUEST newUser = User() newUser.email = userEmail newUser.name = userName newUser.external = data.get('external', None) newUser.active = bool(data.get('active', True)) newUser.schema = user.schema pwo = PasswordGenerator() pwo.minlen = 6 pwo.maxlen = 16 password = pwo.generate() newUser.password = func.crypt(password, func.gen_salt('bf', 8)) if ('admin' in roles): newUser.config = {'roles': data.get('roles', [])} else: newUserRoles = roles.copy() #remove administration roles try: newUserRoles.remove('userAdmin') newUserRoles.remove('admin') newUserRoles.remove("suporte") except ValueError: pass newUser.config = {'roles': newUserRoles} db.session.add(newUser) db.session.flush() response, rstatus = tryCommit(db, newUser.id) if rstatus == status.HTTP_200_OK: sendEmail( "Boas-vindas NoHarm: Credenciais", Config.MAIL_SENDER, [userEmail], render_template('new_user.html', user=userName, email=userEmail, password=password, host=Config.MAIL_HOST)) return response else: updatedUser = User.query.get(idUser) if (updatedUser is None): return { 'status': 'error', 'message': '!Usuário Inexistente!', 'code': 'errors.invalidUser' }, status.HTTP_400_BAD_REQUEST if (updatedUser.schema != user.schema): return { 'status': 'error', 'message': 'Usuário não autorizado', 'code': 'errors.unauthorizedUser' }, status.HTTP_401_UNAUTHORIZED updatedUser.name = data.get('name', None) updatedUser.external = data.get('external', None) updatedUser.active = bool(data.get('active', True)) if ('admin' in roles): if updatedUser.config is None: updatedUser.config = {'roles': data.get('roles', [])} else: newConfig = updatedUser.config.copy() newConfig['roles'] = data.get('roles', []) updatedUser.config = newConfig db.session.add(updatedUser) db.session.flush() return tryCommit(db, updatedUser.id)