async def create_user(user: UserInDB): if db.users.find({'username': user.username}).count() > 0: raise HTTPException(status_code=409, detail="User exists") pwd = get_password_hash(user.hashed_password) user.hashed_password = pwd ret = db.users.insert_one(user.dict(by_alias=True)) user.id = ret.inserted_id return {'user': user}
async def create_user(user: NewUser = Body(...)): user = jsonable_encoder(user) user['hashed_password'] = get_password_hash(user.pop('password', None)) new_user = await mail_db["user"].insert_one(user) created_user = await mail_db["user"].find_one( {"_id": new_user.inserted_id}) return JSONResponse(status_code=status.HTTP_201_CREATED, content=created_user)
def hash_password(cls, value): from auth import get_password_hash if value == "": raise ValidationError("password cannot be empty", model=UserIn) if len(value) <= 2: raise ValidationError("password must have at least 2 characters", model=UserIn) return get_password_hash(value)
async def create_user(user: UserIn, db: Session = Depends(get_db)) -> User: hashed_pw = get_password_hash(user.password) db_user = User(username=user.username, full_name=user.full_name, email=user.email, hashed_password=hashed_pw, is_supervisor=user.is_supervisor) db.add(db_user) db.commit() db.refresh(db_user) return db_user
async def mutate(root, info, phone): # raises error if not valid. ph_formatted = Phone(phone=phone).phone volunteer = await get_volunteer(ph_formatted) if volunteer and volunteer.password: return VolunteerSignUp(status="exists") tpassword = make_password() logger.warn(tpassword) sent = await aero.send_bool( phone, "NEWS", f"{tpassword} is your memedic volunteer code <3") if not sent: return VolunteerSignUp(status="failed") else: if volunteer: volunteer.password = get_password_hash(tpassword) query = (db.volunteer.update().where( db.volunteer.c.uid == volunteer.uid).values( password=volunteer.password)) await database.execute(query) else: volunteer = await create_volunteer(ph_formatted, tpassword) return VolunteerSignUp(status="ok")
async def create_user(user: UserForm, request: Request, response: Response, request_user_id: str = Header(None)): user_in_db = get_user_by_username(user.username) if user_in_db: raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail='There is already another user with this username.', ) user_in_db = get_user_by_email(user.email) if user_in_db: raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail='There is already another user with this email.', ) hashed_password = get_password_hash(user.password) data = user.dict() user_in_db = insert_user(data, hashed_password, request_user_id) return user_in_db
async def handle_user_create(request): data = await request.json() email = data["email"].strip() username = data["username"].strip() password = data["password"].strip() if not auth.validate_username(username): return web.json_response({"error": "invalid username"}, status=400, reason="Bad Request") if not auth.validate_email(email): return web.json_response({"error": "invalid email"}, status=400, reason="Bad Request") if not auth.validate_password(password, username=username, email=email): return web.json_response({"error": "bad password"}, status=400, reason="Bad Request") mode = "test" if request.config_dict["TEST"] else "" users_table = get_table_fullname("users", mode) conn = request.config_dict["DB_CONN"] cursor = await conn.cursor() try: await cursor.execute( """ INSERT INTO {table_fullname} (email, username, pwd_hash) VALUES (?,?,?) """.format(table_fullname=users_table), (email, username, auth.get_password_hash(password)), ) except sqlite3.IntegrityError as exc: await conn.rollback() if "email" in str(exc): return web.json_response( {"error": "user with that email already exists"}, status=409, reason="Conflict", ) if "username" in str(exc): return web.json_response( {"error": "user with that username already exists"}, status=409, reason="Conflict", ) await conn.commit() await cursor.execute( """ SELECT id, username, email FROM {table_fullname} WHERE id = (?) """.format(table_fullname=users_table), [cursor.lastrowid], ) row = await cursor.fetchone() return web.json_response( { "data": { "id": row["id"], "username": row["username"], "email": row["email"], }, }, status=201, reason="Created", )
import sys, os import conf, auth if len(sys.argv) < 3: print('Adds a new user.') print('Usage: %s <username> <password>' % __file__) exit() username = sys.argv[1] password = sys.argv[2] password_hash = auth.get_password_hash(username.encode('utf-8'), password.encode('utf-8')) users_data = auth.get_users() if username in users_data['users'].keys(): print('User %s already exists.' % username) exit() user_id = users_data['new_user_id'] users_data['users'][username] = { 'id': user_id, 'username': username, 'password_hash': password_hash } users_data['user_ids'][user_id] = username users_data['new_user_id'] = user_id + 1 auth.save_users(users_data) print('User %s successfully added.' % username)
def test_hashed_password(self): hashed_pwd = get_password_hash(self.pwd) self.assertTrue(verify_password(self.pwd, hashed_pwd)) self.assertNotEquals(hashed_pwd, self.hashed_pwd)