def main(): db = database.Database() db.connect() if args.passwd_hash is None: # Sloppily pre-check to make sure we don't ask for a password # for an account that will not be valid. Note that since we're # not locking the DB table, it's possible the account becomes # invalid between this check and the actual insert. We do, # however re-check (properly, using transactions) if the account # is valid at insert-time. validate_proposed_user(db, args.user_name, args.real_name, \ args.email_address) # Get password interactively, if necessary while args.passwd_hash is None: # No password (or hash) provided on command line # Ask user for password hash1 = utils.hash_password(getpass.getpass("TOASTER Password for %s: " % \ args.user_name)) hash2 = utils.hash_password(getpass.getpass("Re-type password: "******"Passwords don't match. Try again.\n") user_id = add_new_user(db, args.user_name, args.real_name, \ args.email_address, args.passwd_hash, \ args.is_active, args.is_admin) print "Successfully inserted new user. " \ "Returned user_id: %d" % user_id
def create(self): self.fullname = self.username self.created = time.time() if self.validate(): if User().find_by_username(self.username): self.errors = {'username': u'此用户名已被占用'} return if User().find_by_email(self.email): self.errors = {'email': u'此Email已被注册'} return if not self.password_confirm: self.errors = {'password_confirm': u'确认密码不能为空'} return if self.password != self.password_confirm: self.errors = {'password': u'两次密码输入不一致'} return invite_key = models.Invite_Key().find_by_hash(self.invite_key) if not invite_key: self.errors = {'invite_key': u'该邀请码不存在'} return if invite_key.used: self.errors = {'invite_key': u'该邀请码已被使用'} return del self.password_confirm del self.invite_key self.password = hash_password(self.password) user_id = self.save() signal(EVENTS['USER_CREATE']).send(self, invite_key_hash = invite_key.hash) return user_id
def __init__(self, username, password, email, is_verified = False): self.username = username self.password = hash_password(password) self.email = email self.new_email = email self.is_verified = is_verified self.registered = datetime.utcnow()
def register(): form = RegistrationForm() if request.method == "GET": return render_template("register.html", form=form) elif request.method == "POST": if form.validate_on_submit(): user = User() form.populate_obj(user) # overwrite the old password with a bcrypt-hash user.password = hash_password(user.password) try: user.save() app.logger.info("New user registered") flash("User registered successfully", "success") except IntegrityError as err: app.logger.warning("Could not register user: {0}".format(err)) flash("User could not be registered, please try again", "error") except OperationalError as err: app.logger.warning("MySQL Error: {0!s}".format(err)) flash("{0!s}".format(err)) return redirect(url_for("show_index")) else: flash_errors(form) return render_template("register.html", form=form)
def register_account(ip, username, password, email=None): if Account.objects.filter(username__iexact=username).count() > 0: raise errors.UsernameTakenError(username) account = Account(username=username, password=utils.hash_password(password), email=email, commission_rate=settings.DEFAULT_TRADE_COMMISSION) try: account.full_clean() account.save() except: raise errors.AccountValidationError(username, password, email) # create a balance for each currency for currency in Currency.objects.all(): Balance(account=account, currency=currency).save() # get deposit address for this username from the Bitcoin client # FIXME: shouldn't we do this outside of a DB transaction? conn = utils.get_bitcoin_conn() account.deposit_address = conn.getaccountaddress(username) # generate deposit reference and save again account.deposit_ref = "B" + base64.b32encode(account.id).strip('=') account.save() return {'result': True}
def user_update_profile(): params = utils.flat_multi(request.form) password = params.get("current_password") new_password = params.get("new_password") new_password_confirm = params.get("new_password_confirm") email = params.get("email") if new_password != new_password_confirm: raise WebException("Passwords do not match.") user = get_user(username=session["username"]).first() correct = utils.check_password(user.password, password) if not correct: raise WebException("Incorrect password.") if new_password != "": user.password = utils.hash_password(new_password) if email != user.email: if get_user(email=email.lower()).count() > 0: raise WebException("This email is taken!") user.email = email.lower() user.email_verified = False current_session = db.session.object_session(user) current_session.add(user) current_session.commit() return { "success": 1, "message": "Profile updated." }
def post(self): _login = self.get_body_argument("login") _level = self.get_body_argument("level") _password = self.get_body_argument("password") _is_enabled = self.get_body_argument("is_enabled") if not re.match(r"^[\w.-]{2,32}$", _login): raise HTTPError(400) if _level not in ( BaseHandler.LEVEL_USER, BaseHandler.LEVEL_ADMIN, BaseHandler.LEVEL_SUPER ): raise HTTPError(400) if not self.check_level(BaseHandler.LEVEL_SUPER) and _level == BaseHandler.LEVEL_SUPER: raise HTTPError(400) if _is_enabled not in ("0", "1"): raise HTTPError(400) with self.db.locked() as conn: try: yield self.thread_pool.submit( conn.execute, "INSERT INTO users (login, password, level, is_enabled) VALUES(?)", (_login, utils.hash_password(_password), _level, _is_enabled)) except DBALDriverError: # Error: 1062 (ER_DUP_ENTRY) if conn.error_code() == 1062: raise HTTPError(409) raise self.status_ok()
def create_user(email, name, password): user = User(id=email, name=name, email=email, score=0) user.passwordHash = utils.hash_password(email, password) userKey = user.put() fbook = create_favoritebook(userKey) sbook = create_storybook(userKey) mysbook = create_mystorybook(userKey) return user
def auth(email, password): hashed_pass = hash_password(current_app.config['SALT'], password) try: qry = User.query.filter_by(email = email, password_hash=hashed_pass) g.user = qry.one() return g.user.verified except: return False
def change_password(ip, username, password, new_password): account = Account.objects.select_for_update().get(username=username) account.password = utils.hash_password(new_password) account.full_clean() account.save() return {'result': True}
def change_password(user_id, new_password): pwhash, salt = hash_password(new_password) db.users.update_one({"id": user_id}, {"$set": { "pwhash": pwhash.hex(), "salt": salt.hex() }}) log("password_change", user_id=user_id)
def post(self): data = request.get_json() # 0. 데이터가 전부 다 있는지 체크 if 'username' not in data or 'email' not in data or 'password' not in data: return {'err_code': 1}, HTTPStatus.BAD_REQUEST # 1. 이메일 유효한지 체크 try: # Validate. validate_email(data['email']) except EmailNotValidError as e: # email is not valid, exception message is human-readable print(str(e)) return {'err_code': 3}, HTTPStatus.BAD_REQUEST # 2. 비밀번호 길이체크 및 암호화 if len(data['password']) < 4 or len(data['password']) > 16: return {'err_code': 2}, HTTPStatus.BAD_REQUEST password = hash_password(data['password']) print(password) # 3. 데이터베이스에 저장. ## 실습. 디비에 데이터 인서트 시, 유니크로 인해서 데이터가 # 들어가지 않는 경우를 대비하여, 코드를 수정하세요. try: connection = get_mysql_connection() cursor = connection.cursor() query = """ insert into user (username, email, password) values ( %s, %s, %s );""" param = (data['username'], data['email'], password) cursor.execute(query, param) connection.commit() # 디비에 데이터를 저장한 후, 저장된 아이디값을 받아온다. user_id = cursor.lastrowid # cursor.getlastrowid() print(user_id) except Error as e: print(str(e)) return {'err_code': 4}, HTTPStatus.NOT_ACCEPTABLE cursor.close() connection.close() # JWT 를 이용해서 인증토큰을 생성해 준다. access_token = create_access_token(identity=user_id) return {'token': access_token}, HTTPStatus.OK
def user_create(): user = login_models.User( username=request.form.get('username'), password=utils.hash_password(request.form.get('password')), role_id=request.form.get('role_id'), ) db.session.add(user) db.session.commit() return jsonify(user.serialize()), 201
def add_user(name, password): User = Query() res = app.db.search(User.username == name) if res: return False app.db.insert({'username': name, 'password': utils.hash_password(password)}) return True
def __init__(self, login, name, password, email, role_id): self.login = login self.name = name self.password = hash_password(password) self.email = email self.role_id = role_id # If the user is created, create his upload dir from sharepy.filehandling import create_useruploaddir create_useruploaddir(login)
def user_update(user_id: int): user = login_models.User.query.get_or_404(user_id) user.username = request.form.get('username') password = request.form.get('password') if password is not None and len(password) > 0: user.password = utils.hash_password(password) user.role_id = request.form.get('role_id') db.session.add(user) db.session.commit() return jsonify(user.serialize())
def add_user_to_db(self, login, password): """ Добавление нового пользователя в таблицу пользователей """ session = self._get_session() salt = create_salt() hashed_password = hash_password(salt, password) user = User(login=login, password=hashed_password) session.add(user) session.commit()
def is_user_exist(self, username:str, password:str) -> bool: """Checks if the given username is allowed to connect server.""" if self._db_conn: with self._db_conn: cursor = self._db_conn.cursor() cursor.execute("""SELECT * FROM %s WHERE username=? AND password=?""" % self.tables['users'], (username, utils.hash_password('sha512', password))) return cursor.fetchone() is not None return False
def run(self, data): try: self.__validate(data) self.__check_if_username_exists(data) user = User(data["username"], hash_password(data["password"]), data["name"]) self.__user_repo.add_user(user) return self.__signup_presenter.respond(user) except InvalidUserValuesError as err: logging.error(f"Error signup: {err}") return self.__signup_presenter.respond_with_error(err.message)
def post(self): _login = self.get_body_argument("login") _password = self.get_body_argument("password") user = yield self.thread_pool.submit( self.db.fetch, "SELECT * FROM users WHERE login = ? AND is_enabled = TRUE", _login) if not user or utils.hash_password(_password, user["password"]) != user["password"]: raise HTTPError(401) session = yield self.thread_pool.submit(self.create_session, user["login"]) self.write({"session": session, "level": user["level"]})
def post(self): _login = self.get_body_argument("login") _password = self.get_body_argument("password") if not _password or _login != self.current_user["login"]: raise HTTPError(400) yield self.thread_pool.submit( self.db.execute, "UPDATE users SET password = ? WHERE login = ?", utils.hash_password(_password), _login) self.status_ok()
def get_token(db: Redis, request: BasicCredentials) -> TokenAuth: rcvd_credentials = b64decode(request.data.encode('utf-8')).decode('utf-8') username, password = rcvd_credentials.split(':') db_credentials = db.hgetall(f'{config.CLIENT_PREFIX}{username}') if db_credentials and hash_password(password) == db_credentials['password']: logger.info('username: %s credentials are valid' % username) rpc_token = db_credentials['token'] return TokenAuth(token=rpc_token) else: logger.error('username: %s credentials are invalid!' % username) return TokenAuth(token='')
def register(cls, username, password, email, first_name, last_name, is_provider=False): """Register user w/hashed password & return user.""" # return instance of user w/username and hashed pwd return cls( username=username, password=hash_password(password), email=email, first_name=first_name, last_name=last_name, is_provider=is_provider)
def __init__(self, username: str, password: str, users: dict) -> None: self.username = username self.password = utils.hash_password(username, password) self.points = config.initial_points self.resets = 0 self.victories = { points: 0 for points in iter(config.victory_breakpoints.values()) } users[username] = self # Add to global user dict
def post(self): if not self.is_logged_in(): self.redirect(LOGIN_PAGE_URL) else: customer = Customer.get_by_key_name(self.get_current_username()) if customer.is_password_correct(self.get_argument('old_password')): p = hash_password(self.get_argument('new_password')) customer.password_hash = p[0] customer.password_salt = p[1] customer.put() self.redirect('/dashboard')
def registration(): if request.method == 'GET': return render_template('registration.html', logged_user=session['user_id'], logged_user_name=session['user_name']) new_user_name = request.form['user_name'] if datamanager.check_unique_user_name(new_user_name): return render_template('registration.html', logged_user=session['user_id'], logged_user_name=session['user_name'], message="Already exists!") hashed = utils.hash_password(request.form['password']) datamanager.create_user(new_user_name, hashed) return redirect('/')
def signup(): ref = request if request.method == 'POST': try: username = request.form.get('user_username') email = request.form.get('user_email') password = utils.hash_password(request.form.get('user_password')) firstname = request.form.get('user_firstname') lastname = request.form.get('user_lastname') repeat_password = utils.hash_password(request.form.get('user_repeat_password')) if password != repeat_password: error = " Passwords do not match ! " return render_template('signup.html', error=error) if not utils.valid_username(username): traceback.print_exc() error = " Username is already taken " return render_template('signup.html', error=error) if not utils.valid_email(email): traceback.print_exc() p = re.compile('[aA0-zZ9$]+@[aA0-zZ9]+.[a-z]+') if p.match(email) is None: error = " Email is already taken " else: error = " Invalid Email" return render_template('signup.html', error=error) session['username'] = username # session['password'] = password query = ExploriumDbApi.USERS_TABLE.insert().values(username=username, password=password, email=email, firstname=firstname, lastname=lastname) ExploriumDbApi.conn.execute(query) return render_template('index.html', this_username=session['username'], show_what="Welcome!", result_info_list='') except Exception as e: render_template('signup.html', error='Invalid Input') return render_template('signup.html')
def change_password(self, origin_password, password, password_confirm): if not origin_password: self.add_error(origin_password = u'当前密码不能为空') if not password: self.add_error(password = u'新密码不能为空') if not password_confirm: self.add_error(password_confirm = u'确认密码不能为空') if password != password_confirm: self.add_error(password_confirm = u'两次密码输入不一致') if self.errors: return False if hash_password(origin_password) != self.password: self.add_error(origin_password = u'当前密码不正确') return False self.password = hash_password(password) self.save() return self.saved
def change_password(self, origin_password, password, password_confirm): if not origin_password: self.add_error(origin_password=u'当前密码不能为空') if not password: self.add_error(password=u'新密码不能为空') if not password_confirm: self.add_error(password_confirm=u'确认密码不能为空') if password != password_confirm: self.add_error(password_confirm=u'两次密码输入不一致') if self.errors: return False if hash_password(origin_password) != self.password: self.add_error(origin_password=u'当前密码不正确') return False self.password = hash_password(password) self.save() return self.saved
def test_remove_user_invalid_it(self): username = '******' firstname = 'First Name' lastname = 'Last Name' password = utils.hash_password('password') email = '*****@*****.**' query = ExploriumDbApi.USERS_TABLE.delete().where(ExploriumDbApi.USERS_TABLE.c.username == username) ExploriumDbApi.conn.execute(query) query = ExploriumDbApi.USERS_TABLE.insert().values(username=username, password=password, email=email, firstname=firstname, lastname=lastname) del_res = ExploriumDbApi.remove_user(username, 112391849124321) self.assertEqual(del_res, 'User does not exist')
def update_password(cls, username, password): """Update password""" u = User.query.filter(User.username == username).first() if u: u.password = hash_password(password) db.session.commit() return u else: return False
def signin_api(): email = flask.request.form.get('email') password = flask.request.form.get('password') user = User.fetchone(email=email) if not user: raise error.UserNotExist() if user.password != utils.hash_password(password): raise error.UserPasswordError() return account_signin(user.to_dict())
def __init__(self, name, username, email, password, utype=1, admin=False): self.name = name self.username = username self.username_lower = username.lower() self.email = email.lower() self.password = utils.hash_password(password) self.utype = utype self.admin = admin self.registertime = int(time.time()) self.otp_confirmed = False self.otp_secret = None self.email_verified = False
def put(self): """ Update ip and get new token :return: {id, json web token} """ json_data, error = get_data(request) if not error: device_data, error = validate_json_payload(json_data, self.fields) device_data['ip'] = request.remote_addr if not error: error = self._validate_data( mac=device_data['mac'], ip=device_data['ip'], password=device_data['password'], role_name=device_data['role'] if 'role' in device_data.keys() else None) if not error: device_data['password'] = hash_password( device_data['password']) token = gen_token( {key: device_data[key] for key in self.token_data}) try: role = Role.query.filter_by( role_name=device_data['role'] if 'role' in device_data.keys() else 'Limited').first() jetson = Jetson.query.filter_by( mac=device_data['mac']).first() account = Account.query.filter_by( id=jetson.account_id).first() truck = Truck.query.filter_by( jetson_id=jetson.id).first() except: return response(401, 'Jetson device dosen\'t exists') if jetson.ip != device_data['ip']: jetson.ip = device_data['ip'] + '3' error = jetson.save() if error: return response(500, 'Internal error') if role.id != account.role_id: account.role_id = role.id error = account.save() if not error: return response(200, data={ 'id': account.id, 'truck_id': truck.id, 'token': token }) return error
def update_password(cls, username, password): """Update password""" u = Admin.query.filter(Admin.username == username).first() if u: u.password = hash_password(password) u.pwd_token = "" db.session.commit() return u else: return False
def post(self): # @TODO: Implement PiConsulting: Needs to authenticate OAUTH json_data, error = get_data(request) if not error: username = json_data['username'] user = User.query.filter_by(username=username).first() # @TODO: Validate password account = Account.query.filter_by(id=user.account_id).first() json_data['password'] = hash_password(json_data['password']) token = gen_token(json_data) return response(200, data={'token': token})
def update_password_by_token(cls, token, password): """Update password by token""" u = Admin.query.filter(Admin.pwd_token == token , Admin.is_active==True).first() if u: u.password = hash_password(password) u.pwd_token = "" db.session.commit() return u return False
def check_user(username, password): try: user_from_db = database.return_user(username)[0] except IndexError: return False user = User(user_from_db[1], user_from_db[0], user_from_db[3], user_from_db[4], user_from_db[5]) salt = user_from_db[2].split(',')[1] hashed_password = utils.hash_password(password, salt) if hashed_password == user_from_db[2].split(',')[0]: return user else: return False
def authenticate(self, username=None, password=None): if not (username and password): return False u = User.all()\ .filter("username ="******"password =", hash_password(password)) try: return u.fetch(1)[0] except IndexError: return None
def create_secure_user(session: Session, first_name: str, last_name: str, email: str, password: str) -> User: password_salt = utils.generate_uuid() password_hashed = utils.hash_password(password_raw=password, salt=password_salt) auth_token = utils.generate_uuid() result = crud_user.create_user(session, first_name, last_name, email, password_hashed, password_salt, auth_token) return result
def registration(): if request.method == 'POST': username = request.form.get('username') if data_handler.check_if_user_exist_in_database(username) is False: hashed_password = utils.hash_password(request.form.get('password')) user = data_handler.save_user(username, hashed_password) utils.save_user_session(user) return render_template("index.html", user_name=user[1]) else: error_message = "There's already user with this login" return render_template('index.html', message=error_message) else: return render_template('index.html')
def add_admin_team(name, password, date=None): conn = app.conn if conn is None: return "Could not connect to the database" c = conn.cursor() try: if date is None: date = str(utils.get_time_since_epoch()) c.execute("INSERT into teams VALUES (?, ?, 0, 1, '', '', ?)", (name, utils.hash_password(password), "0,"+date)) conn.commit() except sqlite3.DatabaseError, e: print e return "Could not connect to the database"
def user_forgot_password(token=None): params = utils.flat_multi(request.form) if token is not None: user = get_user(reset_token=token).first() if user is None: raise WebException("Invalid reset token.") # We are viewing the actual reset form if request.method == "GET": return {"success": 1, "message": ""} # Submission of actual reset form if request.method == "POST": password = params.get("password") confirm_password = params.get("confirm_password") if password != confirm_password: raise WebException("Passwords do not match.") else: user.password = utils.hash_password(password) user.reset_token = None current_session = db.session.object_session(user) current_session.add(user) current_session.commit() return {"success": 1, "message": "Success!"} else: email = params.get("email").lower() user = get_user(email=email).first() if user is None: raise WebException("User with that email does not exist.") token = utils.generate_string(length=64) user.reset_token = token current_session = db.session.object_session(user) current_session.add(user) current_session.commit() reset_link = "%s/forgot/%s" % ("127.0.0.1:8000", token) subject = "OpenCTF password reset" body = """%s,\n\nA request to reset your OpenCTF password has been made. If you did not request this password reset, you may safely ignore this email and delete it.\n\nYou may reset your password by clicking this link or pasting it to your browser.\n\n%s\n\nThis link can only be used once, and will lead you to a page where you can reset your password.\n\nGood luck!\n\n- OpenCTF Administrator""" % ( user.username, reset_link) response = utils.send_email(email, subject, body) if response.status_code != 200: raise WebException("Could not send email") response = response.json() if "Queued" in response["message"]: return {"success": 1, "message": "Email sent to %s" % email} else: raise WebException(response["message"])
def post(self): _login = self.get_body_argument("login") _password = self.get_body_argument("password") user = yield self.thread_pool.submit( self.db.fetch, "SELECT * FROM users WHERE login = ? AND is_enabled = TRUE", _login) if not user or utils.hash_password(_password, user["password"]) != user["password"]: self.set_flash("The details you entered are incorrect.", BaseHandler.FLASH_ERROR) self.redirect(self.reverse_url("web_login") + "?login="******"login"]) self.set_secure_cookie("session", session) self.redirect(self.reverse_url("web_index"))
def init(db, settings): db.drop_collection('users') db.users.ensure_index('id', pymongo.ASCENDING, unique=True) if settings['environment'] == 'test': logging.info('Adding test users to database...') res = db.users.insert({ 'username': '******', 'email': '*****@*****.**', 'password': hash_password('simple_password'), 'trusted_email': True, }) if res: logging.info('Added user "simple_user"') res = db.users.insert({ 'username': '******', 'email': '*****@*****.**', 'password': hash_password('simple_password'), 'trusted_email': False, }) if res: logging.info('Added user "simple_user_with_unstrusted_email"')
def create_user(username, password): db = db_client() hashed_pass, salt = hash_password(password) future = db.users.update_one({'username': username}, { '$set': { 'username': username, 'password_hash': hashed_pass, 'salt': salt } }, upsert=True) user = yield future logger.info('Created / Updated user: %s', username) return user
def user_forgot_password(token=None): params = utils.flat_multi(request.form) if token is not None: user = get_user(reset_token=token).first() if user is None: raise WebException("Invalid reset token.") # We are viewing the actual reset form if request.method == "GET": return { "success": 1, "message": ""} # Submission of actual reset form if request.method == "POST": password = params.get("password") confirm_password = params.get("confirm_password") if password != confirm_password: raise WebException("Passwords do not match.") else: user.password = utils.hash_password(password) user.reset_token = None current_session = db.session.object_session(user) current_session.add(user) current_session.commit() return { "success": 1, "message": "Success!" } else: email = params.get("email").lower() user = get_user(email=email).first() if user is None: raise WebException("User with that email does not exist.") token = utils.generate_string(length=64) user.reset_token = token current_session = db.session.object_session(user) current_session.add(user) current_session.commit() reset_link = "%s/forgot/%s" % ("127.0.0.1:8000", token) subject = "OpenCTF password reset" body = """%s,\n\nA request to reset your OpenCTF password has been made. If you did not request this password reset, you may safely ignore this email and delete it.\n\nYou may reset your password by clicking this link or pasting it to your browser.\n\n%s\n\nThis link can only be used once, and will lead you to a page where you can reset your password.\n\nGood luck!\n\n- OpenCTF Administrator""" % (user.username, reset_link) response = utils.send_email(email, subject, body) if response.status_code != 200: raise WebException("Could not send email") response = response.json() if "Queued" in response["message"]: return { "success": 1, "message": "Email sent to %s" % email } else: raise WebException(response["message"])
def test_add_show_comment_invalid_it(self): username = '******' firstname = 'First Name' lastname = 'Last Name' password = utils.hash_password('password') email = '*****@*****.**' query = ExploriumDbApi.USERS_TABLE.delete().where(ExploriumDbApi.USERS_TABLE.c.username == username) ExploriumDbApi.conn.execute(query) query = ExploriumDbApi.USERS_TABLE.insert().values(username=username, password=password, email=email, firstname=firstname, lastname=lastname) ExploriumDbApi.conn.execute(query) add_res = ExploriumDbApi.add_comment(username, 112391849124321, 'Hello World') self.assertNotEqual(add_res, None) comments = ExploriumDbApi.get_itinerary_comments(112391849124321) self.assertEqual(comments, None)
def post(self): first_name = self.get_argument('first_name') last_name = self.get_argument('last_name') email = self.get_argument('email') password = self.get_argument('password') landline_number = self.get_argument('landline_number') mobile_number = self.get_argument('mobile_number') country = self.get_argument('country') city = self.get_argument('city') state_or_province = self.get_argument('state_or_province') area_or_suburb = self.get_argument('area_or_suburb') street_name = self.get_argument('street_name') zip_code = self.get_argument('zip_code') timezone = self.get_argument('timezone') p = hash_password(password) customer = Customer(key_name=email, first_name=first_name, last_name=last_name, email=email, password_hash=p[0], password_salt=p[1], timezone=timezone) #TODO: before saving the profile check if the data is not repeated db.put(customer) landline = Phone(phone_type='landline', number=landline_number, profile=customer) mobile = Phone(phone_type='mobile', number=mobile_number, profile=customer) location = Location(state_or_province=state_or_province, area_or_suburb=area_or_suburb, street_name=street_name, zip_code=zip_code, country=country, city=city, profile=customer) db.put([location, mobile, landline]) self.do_login(email) self.redirect('/dashboard')
def register(): try: if request.is_json: content = request.get_json() else: content = request.form mandatory_fields = ["email", "password"] for _f in mandatory_fields: if _f not in content.keys(): return error("Mandatory fields not given, dumbshit", 400) email = content["email"] password = hash_password(content["password"]) # Dynamic shit omfg meta = {k: v for k, v in content.items() if k not in mandatory_fields} except Exception as e: log.error(e) return error("Bad form data") _target = db.users.find_one({"email": email}) if _target is not None: return error(message="User already exists", code=400) user = { "email": email, "password": password, "meta": meta, "relations": {} } try: _user = db.users.insert_one(user) except Exception as e: log.error(e) return error(message="Could not create user") _jwt = jwt.encode({ "id": str(_user.inserted_id) }, SECRET, algorithm='HS256').decode() return {"token": _jwt}, 200
async def mutate(self, info, login, password): validate_login(login) password = hash_password(password) try: id = await execute_query(''' INSERT INTO account (login, password) VALUES ($1, $2) RETURNING id''', login, password, pg_method='fetchval') except asyncpg.exceptions.UniqueViolationError: raise GraphQLError('That login already exists') return CreateAccount(id=id)
def patch(self, login): _login = self.get_body_argument("login", None) _level = self.get_body_argument("level", None) _password = self.get_body_argument("password", None) _is_enabled = self.get_body_argument("is_enabled", None) values = {} if _login is not None and _login != login: if not re.match(r"^[\w.-]{2,32}$", _login): raise HTTPError(400) values["login"] = _login if _level is not None: if _level not in ( BaseHandler.LEVEL_USER, BaseHandler.LEVEL_ADMIN, BaseHandler.LEVEL_SUPER ): raise HTTPError(400) if not self.check_level(BaseHandler.LEVEL_SUPER) and _level == BaseHandler.LEVEL_SUPER: raise HTTPError(400) values["level"] = _level if _password: values["password"] = utils.hash_password(_password) if _is_enabled is not None: if _is_enabled not in ("0", "1"): raise HTTPError(400) values["is_enabled"] = _is_enabled if not values: raise HTTPError(400) yield self.thread_pool.submit(self._get_user, login) with self.db.locked() as conn: try: yield self.thread_pool.submit( conn.update, "users", values, {"login": login}) except DBALDriverError: # Error: 1062 (ER_DUP_ENTRY) if conn.error_code() == 1062: raise HTTPError(409) raise self.status_ok()
def register(): form = RegistrationForm() if request.method == 'GET': return render_template('register.html', form=form) elif request.method == 'POST': if form.validate_on_submit(): user = User() # overwrite the old password with a bcrypt-hash form.password = hash_password(form.password) form.populate_obj(user) user.save() app.logger.info('New User registered') flash("User registered successfully", 'success') return redirect( url_for('show_index') ) else: flash("Could not register user!", 'error') return render_template('register.html', form=form)
def import_customers(): from utils import hash_password p = hash_password('example') customers_list = ( dict( key_name='*****@*****.**', first_name='Yesudeep', last_name='Mangalapilly', email='*****@*****.**', password_hash=p[0], password_salt=p[1], ), dict( key_name='*****@*****.**', first_name='Tanuj', last_name='Hattangdi', email='*****@*****.**', password_hash=p[0], password_salt=p[1], ), dict( key_name='*****@*****.**', first_name='Aswad', last_name='Rangnekar', email='*****@*****.**', password_hash=p[0], password_salt=p[1], ), dict( key_name='*****@*****.**', first_name="Raj", last_name="Singh", email="*****@*****.**", password_hash=p[0], password_salt=p[1], ), ) customers = [] for c in customers_list: customers.append(Customer(**c)) db.put(customers)
def post(self): username = self.get_argument('username', '') password = self.get_argument('password', '') if not username: return self.redirect(u'/login?error={0}'.format(u"用户名不能为空")) if not password: return self.redirect(u'/login?error={0}'.format(u"密码不能为空")) if username.find('@') != -1: user = models.User().find_by_email(username) else: user = models.User().find_by_username(username) if user: if user.password != hash_password(password): return self.redirect(u'/login?error={0}'.format(u"用户名与密码不符")) else: return self.redirect(u'/login?error={0}'.format(u"该用户不存在")) self.set_secure_cookie('o_O', u'{0}'.format(user.id), domain='.{0}'.format(options.www_domain)) return_url = self.get_argument('return', '/') self.redirect(return_url)
def create(self): self.fullname = self.username self.created = time.time() if self.validate(): if User().find_by_username(self.username): self.errors = {'username': u'此用户名已被占用'} return if User().find_by_email(self.email): self.errors = {'email': u'此Email已被注册'} return if not self.password_confirm: self.errors = {'password_confirm': u'确认密码不能为空'} return if self.password != self.password_confirm: self.errors = {'password': u'两次密码输入不一致'} return del self.password_confirm self.password = hash_password(self.password) user_id = self.save() signal(EVENTS['USER_CREATE']).send(self) return user_id
def login(): """ User login """ form = request.form if request.method == 'POST': organization = Organization.get_by_name(form.get('organization').lower()) # validate user = User.get_by_username(form.get('username'), organization.uuid) if user: if utils.hash_password(form.get('password')) == user.password: login_user(user) session['user'] = user session['organization'] = organization current_app.logger.info('User {0} ({1}) login from {2}'.format(user.username, organization.name, \ request.remote_addr)) return redirect(request.args.get("next") or url_for("index")) current_app.logger.warn('Invalid login for {0} ({1}) from {2}'.format(form.get('username'), organization.name, \ request.remote_addr)) flash(messages.INVALID_USERNAME_OR_PASSWORD, 'error') ctx = { } return render_template('accounts/login.html', **ctx)
def create_user(email, name, wpc_name, password): user = User(id=wpc_name, name=name, wpc_name=wpc_name, email=email, score=0) user.passwordHash = utils.hash_password(wpc_name, password) userKey = user.put() return user