def post(self): user_data = UserRegister.parser.parse_args() if UserModel.find_by_username(username=user_data['username']): return {'message': 'A user with username already exists'}, 400 user = UserModel(user_data['username'], user_data['password']) user.save_to_db() return {"message": "user created successfully"}, 201
async def create_user(user: UserRequest, db: Session = Depends(database.get_db_session), current_user: LoginSchema = Depends( oauth.get_current_user)): created = datetime(datetime.today().year, datetime.today().month, datetime.today().day) password = Hash.bcrypt(user.password) new_user = UserModel(username=user.username, password=password, name=user.name, lastname=user.lastname, email=user.email, enabled=user.enabled, created=created) db.add(new_user) db.commit() db.refresh(new_user) if not new_user: raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail='Error trying to create blog!') return new_user
def post(cls): data = request.get_json() if UserModel.find_by_email(data["email"]): return { "message": response_quote("user_email_taken") }, 400 # TODO: user = UserModel(username=data["username"], password=b_crypt.generate_password_hash( data["password"]).decode("utf-8"), email=data["email"], sha_private=hashlib.sha256(str.encode( data["email"])).hexdigest()) try: user.save_to_db() confirmation = ConfirmationModel(user.id) confirmation.save_to_db() user.confirm() return {"message": response_quote("user_been_created")}, 201 except MailGunException as e: user.delete_from_db() # rollback return {"message": str(e)}, 500 except: traceback.print_exc() user.delete_from_db() return {"message": response_quote("operation_fatal_error")}, 500
def post(args): if not safe_str_cmp(args['password'], args['password_confirmation']): return { 'success': False, 'errors': { 'password': ['Password and password confirmation do not match'] } }, 409 user = UserModel.find_by_email(args['email']) if user: return { 'success': False, 'error': 'Email has already been taken' }, 409 is_admin = False if UserModel.count_all() < 1: is_admin = True phone = None if 'phone' in args: phone = args['phone'] hashed_password = UserModel.generate_hash(args['password']) user = UserModel(args['name'], hashed_password, args['email'], phone, is_admin) user.save_to_db() return {'success': True, 'user': user_summary.dump(user).data}, 201
def create_tables(): print('Creating all application tables') db.create_all() if (seed_database): print('Seeding database') characters = [ CharacterModel(name='Aragorn Segundo Elessar', race='men', age='210'), CharacterModel(name='Gandalf', race='Maia', age=''), CharacterModel(name='Sauron', race='Maia', age=''), CharacterModel(name='Bilbo Baggins', race=' Hobbit', age=''), ] for character in characters: character.save_to_db() users = [ UserModel( username='******', password='******' ), ] for user in users: user.save_to_db()
def post(self): data = _user_parser.parse_args() if UserModel.find_by_username(data['username']): return {'message': 'username is already exists'}, 400 user = UserModel(**data) user.save_to_db() return {'message': 'User created successully.'}, 201
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']): return {"message": "Un utilizator cu acest nume deja exista"}, 400 user = UserModel(**data) user.save_to_db() return {"message": "Utilizatorul a fost creat."}, 201
def post(self): data = request.json if UserModel.find_by_username(data['username']): return {'message': 'A user with that username already exists'}, 400 user = UserModel(data['username'], data['password']) user.save_to_db() return 201
def put(self, username): # gets current identity (username, password, admin, super_user) identity = current_identity # loads json data and parses looking for args data = User.parser.parse_args() # existing user needed to query if a change being made to username already exists existing_user = UserModel.find_by_username(data['username']) # looks for current username passed in '/user/<name>' exists and if not create user = UserModel.find_by_username(username) if identity.super_user == 0 and identity.username != username: return {'message': 'You are not authorized.'}, 403 if user is None: user = UserModel(data['username'].lower(), data['password'], data['site_location'].lower(), data['admin'], data['super_user'], identity.username.lower()) else: # it existed, now we must check a few other things to update a record # user is admin and no existing user if identity.super_user == 1 and existing_user is None: user.username = data['username'].lower() user.password = data['password'] user.site_location = data['site_location'].lower() user.admin = data['admin'] user.super_user = data['super_user'] user.created_by = identity.username.lower() # user is updating his record but changing his username elif identity.username == username and existing_user is None: user.username = data['username'].lower() user.password = data['password'] user.site_location = data['site_location'].lower() user.admin = user.admin user.super_user = user.super_user user.created_by = identity.username.lower() # user is updating his user record without a name change elif identity.username == existing_user.username: user.username = data['username'].lower() user.password = data['password'] user.site_location = data['site_location'].lower() if identity.super_user == 1: user.admin = data['admin'] user.super_user = data['super_user'] else: user.admin = user.admin user.super_user = user.super_user user.created_by = identity.username.lower() else: return {'message': 'Username is already in use'}, 400 user.save_to_db() return user.json()
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']) is not None: return {"message": "User with this name already exists!"}, 400 password_hash = generate_password_hash(data['password']) user = UserModel(data['username'], password_hash) user.save_to_db() return {"message": "User created successfully"}, 201
def post(self): data = _user_parser.parse_args() if UserModel.find_by_username(data['username']): return {"message": "A user with that username already exists"}, 400 user = UserModel(data['username'], data['password']) user.save_to_db() return {"message": "User created successfully."}, 201
def post(self): data = UserRegister.parser.parse_args() user = UserModel.find_by_email(data['email']) if user: return {'message': "User already exists"}, 400 user = UserModel(data['email'], data['password']) user.save() return {'message': 'User is created'}, 201
def crear_usuario(): if request.method == 'GET': return render_template('usuarios/crear.html') nombre = request.form.get('nombre') apellido = request.form.get('apellido') celular = request.form.get('celular') email = request.form.get('email') password = request.form.get('password') usuariosModel = UserModel() usuariosModel.crear_usuario(nombre, apellido, celular, email, password) return redirect(url_for('usuarios'))
def add_users(): data = request.get_json() newUser = UserModel(username=data['username'], password=UserModel.generate_hash(data['password'])) try: newUser.save_to_db() return jsonify( {'message': 'User {} was created'.format(data['username'])}) except SQLException.IntegrityError: return jsonify({'message': 'This username is already in use'}), 409 except Exception as e: print('Exception: ', e) return jsonify({'message': 'Something went wrong'}), 500
def post(cls): data = UserRegister.parser.parse_args() is_valid, msg = cls.validate_username_input(data['username']) if not is_valid: return {'message': msg}, 400 is_valid, msg = cls.validate_password_input(data['password']) if not is_valid: return {'message': msg}, 400 if UserModel.find_by_username(data['username']) is not None: return {'message': MSG.EXISTED.format(data['username'])}, 400 data['hashed_password'], data['salt'] = encoder(data['password']) user = UserModel(**data) user.save_to_db(user) return {'message': MSG.REGISTERED.format(data['username'])}, 201
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data["username"]): return { "message": "User with this name is already registered" }, 400 try: user = UserModel(**data) user.save_to_db() except: return {"message": "An error occurred registering the user."}, 500 return {"message": "User created successfully."}, 201
def post(self): data = request.get_json() if UserModel.find_by_username(data['username']): return {"message": "Username already exists"}, 400 user = UserModel(**data) user.save_to_db() # connection = sqlite3.connect('mydata.db') # cursor = connection.cursor() # # query = "insert into users values (NULL,?,?)" # cursor.execute(query,(data['username'],data['password'])) # # connection.commit() # connection.close() return {"message": "user created successfully"}, 201
def post(self): parser = reqparse.RequestParser() parser.add_argument('username', help='This field cannot be blank', required=True, type=str) parser.add_argument('password', help='This field cannot be blank', required=True, type=str) parser.add_argument('email', help='This field cannot be blank', required=True, type=str) data = parser.parse_args() if UserModel.find_by_username(data['username']): abort(409, message=USER_ALREADY_EXISTS) if len(data['username']) < 3: abort(400, message=USERNAME_TOO_SHORT) if not re.match(username_regex, data['username']): abort(400, message=USERNAME_INVALID) if not re.match(email_regex, data['email']): abort(400, message=EMAIL_INVALID) if len(data['password']) < 8: abort(400, message=PASSWORD_TOO_SHORT) new_user = UserModel( username=data['username'], password=UserModel.generate_hash(data['password']), email=data['email'] ) new_account_settings = AccountSettingsModel() try: new_user.persist() new_account_settings.user_id = new_user.id new_account_settings.persist() access_token = create_access_token(identity=data['username']) refresh_token = create_refresh_token(identity=data['username']) return AuthResponse( USER_CREATION_SUCCESS, new_user, access_token=access_token, refresh_token=refresh_token), 201 except: abort(500, message=INTERNAL_SERVER_ERROR)
def post(self): data = self.parser.parse_args() username = data['username'] if username == "admin": if UserModel.set_master_admin(data['password'], 4): return { 'user': UserModel.find_by_username(username).json() }, 201 else: return {'message': 'Admin already set.'}, 400 if UserModel.find_by_username(username): return {"message": f"User {username} already exists."}, 400 user = UserModel(**data) user.save() return {"message": f"User {username} registered."}, 201
def test_crud(self): with self.app_context(): user = UserModel('test_username', 'A12345678') self.assertIsNone( UserModel.find_by_username('test_username'), "Found an user with name 'test_username' before save_to_db") self.assertIsNone(UserModel.find_by_id(1), "Found an user with id '1' before save_to_db") user.save_to_db() self.assertIsNotNone( UserModel.find_by_username('test_username'), "Did not find an user with name 'test_username' after save_to_db" ) self.assertIsNotNone( UserModel.find_by_id(1), "Did not find an user with id '1' after save_to_db")
def post(self): data = UserRegister.parser.parse_args() if data['username'] is "" or data['password'] is "": return { "message": "Username or Password field cannot be blank" }, 400 elif data['username'] is " " or data['password'] is " ": return { "message": "Username or Password field cannot be blank" }, 400 if UserModel.find_by_username(data['username']): return {"message": "A user with that username already exists"}, 400 user = UserModel(data['username'].lower(), data['password'], data['site_location'].lower(), False, False, data.username.lower()) user.save_to_db() return {"messgae": "User created successfully."}, 201
def register(): form = RegisterForm() if form.validate_on_submit(): user = UserModel() user.name = form.name.data user.email = form.email.data user.password = generate_password_hash(form.password.data) try: session_to_add(user) flash(message="Usuário criado com sucesso!", category="success") except: flash(message="Erro, email já cadastrado.", category="warning") return redirect(url_for("register")) return redirect(url_for("login")) return render_template("register.html", form=form)
def create_user(user: UserCreate, db: Session = Depends(get_db)): """ Create one user :param user: UserCreate model :param db: DB session :return: Created user """ user = UserModel(**user.dict()) # Hash password key = hashlib.pbkdf2_hmac( 'sha256', user.password.encode('utf-8'), os.urandom(32), # Salt 100000) # Number of iteration # Commit to DB db.add(user) db.commit() db.refresh(user) return {"id": str(user.id), "name": user.name}
def get(cls): response = github.authorized_response() g.access_token = response['access_token'] github_user = github.get('user') github_username = github_user.data['login'] user = UserModel.find_by_username(github_username) if not user: user = UserModel( username=github_username, password="******", email="*********", sha_private=hashlib.sha256(str.encode(github_username)).hexdigest() ) user.save_to_db() access_token = create_access_token(identity=user.sha_private, expires_delta=EXPIRES_DELTA) refresh_token = create_refresh_token(identity=user.sha_private) return { "access_token": access_token, "refresh_token": refresh_token }, 200
def post(cls): data = request.get_json() if UserModel.find_by_email(data["email"]): return {"message": response_quote("user_email_taken")}, 400 password_salt, password_hash = PassCrypt.generate_password_hash( data["password"]) user = UserModel(username=data["username"], password_hash=password_hash, password_salt=password_salt, email=data["email"]) try: user.save_to_db() confirmation = ConfirmationModel(user.id) confirmation.save_to_db() user.confirm() return {"message": response_quote("user_been_created")}, 201 except MailGunException as e: user.delete_from_db() # rollback return {"message": str(e)}, 500 except: traceback.print_exc() user.delete_from_db() return {"message": response_quote("operation_fatal_error")}, 500
def post(cls) -> tuple: """ Add a new user to the data base. :return: {json_message}, status code """ data = cls.parser.parse_args() if UserModel.find_by_username(data['username']): return { "message": "A user '{}' already exists!".format(data['username']) }, 400 # Hashing: incl. 16-byte salt (auto) + 29.000 iterations (default) data['password'] = pbkdf2_sha256.hash(data['password']) user = UserModel(** data) # UserModel(data['username'], data['password']) user.save_to_db( ) # Because we use a parser we can use **data! Its never gonna have more/less arguments return {"message": "User created successfully."}, 201
def post(self): user = UserModel(username=ns.payload.get('username'), password=ns.payload.get('password')) user.save() return user.as_dict(), 201
from src.config.hash import check from flask_restful import Resource,reqparse from src.models.user import UserModel from flask_jwt_extended import create_access_token,jwt_required, get_jwt_identity UserModel=UserModel() class User(Resource): parser=reqparse.RequestParser() parser.add_argument('password',required=True) parser.add_argument('username') parser.add_argument('new_password') def post(self):#login args=User.parser.parse_args() user=UserModel.find_one(args['username']) if(not user): return "Not Found", 404 elif(check(args['password'],user['password'])): return create_access_token(identity=user['username']),200 else: return "Unauthorized",401 @jwt_required() def put(self):#altera senha args=self.parser.parse_args() user=UserModel.find_one(get_jwt_identity()) if(not user): return "Not Found", 404 elif(check(args['password'],user['password'])): UserModel.update(get_jwt_identity(),args['new_password']) return "Ok",200
def usuarios(): usuariosModel = UserModel() usuarios = usuariosModel.traerTodos() return render_template('usuarios/index.html', usuarios=usuarios)