def create_user(self): u = User(_DBCON) u.email = self.EMAIL u.password = self.PASSWORD u.save() return u
def main(): print 'Hello World' myDB = MysqlPython('thinkman-wang.com', 'thinkman', 'Ab123456', 'db_thinknews') szSql = 'select * from user' result = myDB.select_advanced(szSql) for obj in result : user = User() user.id, user.user_name, user.password = obj print("%d | %s | %s" % (user.id, user.user_name, user.password)) lstUser = get_all_users() for user in lstUser : print("%d | %s | %s" % (user.id, user.user_name, user.password)) lstUser = get_all_user_from_pool(); for user in lstUser : print("%d | %s | %s" % (user.id, user.user_name, user.password)) print obj2json(lstUser) user = login("18621675203", "a0a475cf454cf9a06979034098167b9e") if (user != None): print obj2json(user) else: print("login failed") szToken = ("%s%d" % ("a0a475cf454cf9a06979034098167b9e", int(time.time()))) print(hashlib.md5(szToken).hexdigest())
def get(self, *args, **kwargs): self.errors = [] # перезагружаем конфигурацию приложения self.application.loadConfiguration() self.removeDBSessions() # миграция БД password = None try: connection = self.getDBSession() migrate(connection = connection) except BaseException as exception: self.errors.append(u'Ошибка при миграции БД: ' + exception.message) else: # create admin user password = hashlib.sha256(str(time.time())).hexdigest()[5:11] user = User() user.fullname = 'Admin' user.login = '******' user.password = hashlib.sha256(password).hexdigest() user.role = User.ROLE_ADMIN try: connection.merge(user) connection.commit() except BaseException as exception: self.errors.append(u'Ошибка при создани пользователя: ' + exception.message) else: self.application.isInstalled = True self.render('install/end.jinja2', {'errors': self.errors, 'admin_pass': password})
def init_QA(): is_student_exist = False is_lecturer_exist = False qa_student = User(username='******', name='Student QA', avatar_url='http://ava.com', email='*****@*****.**', isLecturer=False, accessToken='student_token_', seToken='_QA_TOKEN_TEST_STUDENT') qa_lecturer = User(username='******', name='Student QA', avatar_url='http://ava.com', email='*****@*****.**', isLecturer=True, accessToken='student_token_', seToken='_QA_TOKEN_TEST_LECTURER') query = User.all().filter('username ='******'username =', qa_lecturer.username) for u in query.run(): is_lecturer_exist = True u.isLecturer = qa_lecturer.isLecturer u.seToken = qa_lecturer.seToken u.campuses_id_list = [] u.classes_id_list = [] db.put(u) if not is_lecturer_exist: db.put(qa_lecturer) if not is_student_exist: db.put(qa_student) return Response(status=200)
def testValidEmail(self): e, err = User.valid_email(email1) self.assertEqual(e, True, "With no existing user") u = User.save(username1, email1, password1) # u.put() e, err = User.valid_email(email1) self.assertEqual(e, False, "After create user with the email being tested")
def index(): e = bottle.request.POST.get('email') p1 = bottle.request.POST.get('password1') p2 = bottle.request.POST.get('password2') if e and p1 and p2: if p1 != p2: return bottle.template('register', error='The passwords do not match', email=e, password1=p1, password2=p2) else: u = User(_DBCON, email=e, password=p1) if u._id: return bottle.template('register', error='An account already exists for that email address', email=e, password1=p1, password2=p2) else: u.save() e = Email(recipient=e) e.send('Places accounts activation', '<a href="%s/activate/%s">Activate</a>' % (settings.BASEURL, u.token)) return bottle.redirect('/success') else: vd = { #'date':datetime.datetime.now().strftime('%Y'), 'baseurl':settings.BASEURL, } return bottle.template('register', error='Please complete the form', email=e or '', password1=p1 or '', password2=p2 or '', vd=vd)
def contribution_requests_refuse(): contribution_request_id = request.form.get('contribution_request_id', -1) contribution_request = Contribution_Request.select_by_id(contribution_request_id, 1) if len(contribution_request) is not 0: contribution_request = contribution_request[0] tale = Tale.select_by_id(contribution_request['tale_id'], 1)[0] if tale['creator_id'] is session.get('user_logged_id', None): Contribution_Request.update_was_accepted(contribution_request['id'], False) Tale.update_contribution_request_count(contribution_request['tale_id'], -1) creator = User.select_by_id(tale['creator_id'], 1)[0] contributor = User.select_by_id(contribution_request['user_id'], 1)[0] email_object = strings.construct_contribution_request_refused_email_object( session.get('language', 'en'), tale, creator, contributor, contribution_request['id'] ) aux.send_email_to_followers(tale['id'], email_object['title'], email_object['body']) return redirect('/tale/' + str(contribution_request['tale_id']) + '/0') else: return redirect('/404') else: return redirect('/404')
def change_password_post(): random_token = request.form.get('change-password-random-token', '') p_c_r = Password_Change_Requests.select_by_id(random_token, 1) if request.is_xhr and len(p_c_r) is not 0 and Password_Change_Requests.is_valid_random_token(p_c_r[0]['datetime']): p_c_r = p_c_r[0] new_password = request.form.get('change-password-new-password', '') confirm_new_password = request.form.get('change-password-confirm-new-password', '') language = session.get('language', 'en') error_list = list() if not User.is_password_valid(new_password): error_list.append(strings.STRINGS[language]['INVALID_PASSWORD']) if new_password != confirm_new_password: error_list.append(strings.STRINGS[language]['PASSWORD_NO_MATCH']) if len(error_list) is not 0: return make_response(jsonify(error_list = error_list), 400) else: User.update_password(p_c_r['user_id'], new_password) Password_Change_Requests.delete(p_c_r['user_id']) session['user_logged_id'] = p_c_r['user_id'] username = User.select_by_id(p_c_r['user_id'], 1)[0]['username'] return jsonify(url = '/profile/' + username) else: return redirect('/404')
def invite_post(tale_id): username = request.form.get('invite-username', '') user = User.select_by_email(username, 1) tale = Tale.select_by_id(tale_id, 1) if len(user) is 0: user = User.select_by_full_username(username, 1) if len(user) is not 0 and len(tale) is not 0 and session.get('user_logged_id', None) is tale[0]['creator_id']: user = user[0] tale = tale[0] new_invitation = Invitation(session['user_logged_id'], user['id'], tale_id) new_invitation.insert() creator = User.select_by_id(tale['creator_id'], 1)[0] email_object = strings.construct_tale_invitation_email_object( session.get('language', 'en'), user, tale, creator ) aux.send_email(email_object['title'], user['email'], email_object['body']) return redirect('/tale/' + str(tale_id) + '/0')
def post(self, *args, **kwargs): user_uuid = self.get_argument('uuid', '') user = User.by_uuid(user_uuid) if user is not None: errors = [] username = self.get_argument('username', None) password = self.get_argument('password', None) if password is not None: if 12 <= len(password) <= 100: self.change_user_password(user) else: errors.append("Password invalid length (12-100)") if username is not None and username != user.username: if 3 <= len(username) <= 15: if User.by_username(username) is None: user.username = username dbsession.add(user) dbsession.flush() else: errors.append("Username already exists") else: errors.append("Username is an invalid length (3-15)") self.render("admin/manage_users.html", errors=errors) else: self.render("admin/manage_users.html", errors=["User does not exist"] )
def setUp(self): self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0) self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub(consistency_policy=self.policy) self.u1 = User.save(username1, email1, password1) self.u2 = User.save(username2, email2, password2)
def post(self, *args, **kwargs): ''' Attempts to create an account, with shitty form validation ''' # Check user_name parameter try: user_name = self.get_argument('username') except: self.render('public/registration.html', errors = 'Please enter a valid account name') # Check handle parameter try: handle = self.get_argument('handle') except: self.render('public/registration.html', errors = 'Please enter a valid handle') # Check password parameter try: password1 = self.get_argument('pass1') password2 = self.get_argument('pass2') if password1 != password2: self.render('public/registration.html', errors = 'Passwords did not match') else: password = password1 except: self.render('public/registration.html', errors = 'Please enter a password') # Check recaptcha try: response = captcha.submit( self.get_argument('recaptcha_challenge_field'), self.get_argument('recaptcha_response_field'), self.application.settings['recaptcha_private_key'], self.request.remote_ip,) except: self.render('public/registration.html', errors = "Please fill out recaptcha!") # Create account if User.by_user_name(user_name) != None: self.render('public/registration.html', errors = 'Account name already taken') elif user_name == handle: self.render('public/registration.html', errors = 'Account name and hacker name must differ') elif User.by_display_name(handle) != None: self.render('public/registration.html', errors = 'Handle already taken') elif not 0 < len(password) <= 7: self.render('public/registration.html', errors = 'Password must be 1-7 characters') elif not response.is_valid: self.render('public/registration.html', errors = 'Invalid Recaptcha!') else: char_white_list = ascii_letters + digits user_name = filter(lambda char: char in char_white_list, user_name) display_name = filter(lambda char: char in char_white_list, handle) user = User( user_name = unicode(user_name), display_name = unicode(display_name), password = password ) self.dbsession.add(user) self.dbsession.flush() self.redirect('/login')
def activate_token(self, token): u = User(_DBCON) if u.activate(token): self._login_user(u) else: self.viewdata.update({"error": "The token does not match any account that is pending activation"}) return self._template("error")
def new_users(): users = json.loads(request.data) users = users['users'] session = Session() for user in users: User.get_or_create_temp(session, user) return jsonify({'received': 'true'})
def test_activate_user_good_token(self): self.create_user() user = _DBCON.User.find_one() u = User(_DBCON) self.assertTrue(u.activate(user['token'])) self.assertTrue(u.valid) self.assertTrue(u.email == self.EMAIL)
def get(self, username): """display profile of user with username, if None, display logged in user """ mode = self.request.get('mode') upload_url = "" if mode == 'add_project': template = 'profile/add_project.html' upload_url = blobstore.create_upload_url('/' + username, max_bytes_per_blob=self.MAX_IMG_SIZE) elif mode == 'edit_project': template = 'profile/edit_project.html' upload_url = blobstore.create_upload_url('/' + username, max_bytes_per_blob=self.MAX_IMG_SIZE) elif mode == 'edit': template = 'profile/edit.html' else: template = 'profile/profile.html' user = User.get_user(username) if not user: user = User.save(username, '{}@someplace.com'.format(username), 'some long password') gravatar = user.avatar_url friends = [] if user: all, ic, cc = self.organize_courses_for(user) if user.dob: dob = user.dob.strftime('%m/%d/%Y') else: dob = None projects = Project.get_projects_by_ids(user.projects) context = {'user': user, 'dob': dob, 'username': username, 'gravatar': gravatar, 'friends': friends, 'friend_btn': False, 'courses_all': Course.courses_to_dict(), 'courses_completed': cc, 'courses_incomplete': ic, 'projects': projects, 'upload_url': upload_url, 'errors': {}} self.render(template, context) else: self.redirect('/logout')
def register(): if request.method=="GET": return render_template("register.html") elif request.method=="POST": user_name=request.form["username"] password=request.form["password"] user=User(user_name,password,time.strftime("%Y-%m-%d %T"),None) User.add(user) session["user"]=serials.getDict(user) return redirect(url_for("vip.index"))
def create_user(): user = User.by_handle("HacKer") if user is None: user = User() user.handle = "HacKer" user.password = "******" user.bank_password = "******" dbsession.add(user) dbsession.commit() return user
def test_password_is_still_the_same_after_user_instance_being_saved(self): u = self.create_activated_user() u = User(_DBCON, email=self.EMAIL, password=self.PASSWORD) u.save() #now try and get that user again with the same email and password u = User(_DBCON, email=self.EMAIL, password=self.PASSWORD) self.assertTrue(u._id is not None)
def create_user(self): ''' Add user to the database ''' if User.by_handle(self.get_argument('handle', '')) is not None: raise ValidationError("This handle is already registered") if self.get_argument('pass1', '') != self.get_argument('pass2', ''): raise ValidationError("Passwords do not match") user = User() user.handle = self.get_argument('handle', '') user.password = self.get_argument('pass1', '') user.bank_password = self.get_argument('bpass', '') user.name = self.get_argument('playername', '') user.email = self.get_argument('email','') team = self.get_team() self.dbsession.add(user) self.dbsession.add(team) self.dbsession.commit() # Avatar avatar_select = self.get_argument('user_avatar_select', '') if avatar_select and len(avatar_select) > 0: user._avatar = avatar_select elif hasattr(self.request, 'files') and 'avatar' in self.request.files: user.avatar = self.request.files['avatar'][0]['body'] team.members.append(user) if not options.teams: if avatar_select and len(avatar_select) > 0: team._avatar = avatar_select elif hasattr(self.request, 'files') and 'avatar' in self.request.files: team.avatar = self.request.files['avatar'][0]['body'] self.dbsession.add(user) self.dbsession.add(team) self.dbsession.commit() self.event_manager.user_joined_team(user) return user
def test_change_password_bad(self): u = self.create_activated_user() u = User(_DBCON, email=self.EMAIL, password=self.PASSWORD) u.password = '******' u.save() #now try and get that user again with the new email and password u = User(_DBCON, email=self.EMAIL, password='******') self.assertTrue(u._id is None)
def delete_account(random_token): signup_queue = Signup_Queue.select_by_id(random_token, 1) if len(signup_queue) is not 0: signup_queue = signup_queue[0] Signup_Queue.delete(signup_queue['user_id']) User.delete_account(signup_queue['user_id']) return redirect('/') else: return redirect('/404')
def get(self, uuid=None): ''' Get a specific user or all users ''' if uuid is None: response = json.dumps([user.to_dict() for user in User.all()]) else: user = User.by_uuid(uuid) if user is not None: response = user.to_dict() else: self.set_status(BAD_REQUEST) response = {"error": "User not found"} self.write(response)
def done(self): #make sure the user doesn't already exist u = User.by_name(self.username) if u: msg = 'That user already exists.' self.render('signup.html', error_username = msg) else: u = User.register(self.username, self.password, self.email) u.put() self.login(u) self.redirect("/wiki/") self.render("welcome.html", username = self.username)
def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() # make sure you know what this does self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1) self.testbed.init_datastore_v3_stub(consistency_policy=self.policy) self.u1 = User.save(username1, email1, password1) self.u2 = User.save(username2, email2, password2) self.createNewSource() self.createNewCourses() self.courses = self.createNewAttempts()
def activate_account(random_token): signup_queue = Signup_Queue.select_by_id(random_token, 1) if len(signup_queue) is not 0: signup_queue = signup_queue[0] Signup_Queue.delete(signup_queue['user_id']) User.activate_account(signup_queue['user_id']) flash('The Account was activated successfully.') return redirect('/join') else: return redirect('/404')
def get_all_users() : myDB = MysqlPython('thinkman-wang.com', 'thinkman', 'Ab123456', 'db_thinknews') szSql = 'select * from user' result = myDB.select_advanced(szSql) lstUser = [] for obj in result : user = User() user.id, user.user_name, user.password = obj lstUser.append(user) return lstUser
def post(self, *args, **kwargs): user = User.by_name(self.get_argument('username', '')) password = self.get_argument('password', '') if user is not None: if user.validate_password(password): self.login_success(user) self.redirect('/user') else: self.login_failure() else: # Prevent user enumeration via timing attack User._hash_password(password) self.login_failure()
def create_user(self, team): ''' Add user to the database ''' if self.get_argument('pass1', '') != self.get_argument('pass2', ''): raise ValidationError("Passwords do not match") user = User() user.handle = self.get_argument('handle', '') user.password = self.get_argument('pass1', '') user.bank_password = self.get_argument('bpass', '') team.members.append(user) self.dbsession.add(user) self.dbsession.add(team) self.dbsession.commit() self.event_manager.user_joined_team(user) return user
def register(): form = RegisterForm(request.form) if request.method == 'POST': if not form.validate(): return render_template('register.html', form=form, user=get_user()) else: new_user = User(form.email.data, form.password.data) new_user.timestamp = datetime.datetime.utcnow() db.session.add(new_user) db.session.commit() session['email'] = new_user.email return redirect(url_for('index')) else: return render_template('register.html', form=form, user=get_user())
def transfer(self): user = self.get_current_user() source = Team.by_name(self.get_argument('source', '')) destination = Team.by_name(self.get_argument('destination', '')) try: amount = int(self.get_argument('amount', 0)) except ValueError: amount = 0 victim_user = User.by_handle(self.get_argument('user', None)) password = self.get_argument('password', '') user = self.get_current_user() # Validate what we got from the user if source is None: self.write({"error": "Source account does not exist"}) elif destination is None: self.write({"error": "Destination account does not exist"}) elif victim_user is None or not victim_user in source.members: self.write({"error": "User is not authorized for this account"}) elif victim_user in user.team.members: self.write({"error": "You cannot steal from your own team"}) elif not 0 < amount <= source.money: self.write({ "error": "Invalid transfer amount; must be greater than 0 and less than $%d" % source.money }) elif destination == source: self.write( {"error": "Source and destination are the same account"}) elif victim_user.validate_bank_password(password): logging.info("Transfer request from %s to %s for $%d by %s" % (source.name, destination.name, amount, user.handle)) xfer = self.theft(victim_user, destination, amount, password) self.write({ "success": "Confirmed transfer to '%s' for $%d (after 15%s commission)" % ( destination.name, xfer, '%', ) }) else: self.write({"error": "Incorrect password for account, try again"}) self.finish()
def get_user(self, username): """ :type username: username String """ try: self.cur.execute("SELECT * FROM app_user WHERE username = %s", (username, )) result = self.cur.fetchone() if result is not None: user = User(result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7]) logging.info("Got user: "******" from database") else: user = None return user except Error as e: logging.exception("Error getting user: " + username)
def test_create_user(self): username = "******" dbconn = Db() now = datetime.now() formatted_date = now.strftime('%Y-%m-%d %H:%M:%S') user = User(username, "userpassword", "testchannel", "testbot", "testbotOAuth", "channelToken", formatted_date, formatted_date) exists = dbconn.get_user(user.username) self.assertEqual(exists, None) dbconn.create_user(user) exists_now = dbconn.get_user(user.username) self.assertEqual(exists_now.username, user.username) self.cleanup()
def leaderboard(cls, order_by='passwords'): ''' Creates an ordered list of tuples, for each user and the number of password they've cracked ''' orders = {'passwords': 1, 'cash': 2} leaders = [] for user in User.all_users(): if 0 < cls.count_cracked_by(user.id): leaders.append(( user, cls.count_cracked_by(user.id), sum(cls.by_cracker_id(user.id)), )) if order_by not in orders: order_by = 'passwords' leaders.sort(key=lambda stats: stats[orders[order_by]], reverse=True) return leaders
def register(): email = request.form['email'] existing_user = User.query.filter_by(email=email).first() if existing_user: return { 'message': 'Email already exists' }, 409 else: first_name = request.form['first_name'] last_name = request.form['last_name'] email = request.form['email'] password = request.form['password'] user = User(first_name=first_name, last_name=last_name, email=email, password=password) db.session.add(user) db.session.commit() return { 'message': 'User created successfully' }, 201
def testDeleteConversationWithOneMsgAndOwner(self): c, msg = User.add_new_conversation(self.u1.username_norm, self.u2.username_norm, title_plain_text, content_plain_text) self.assertEqual(len(c.messages_list), 1, "1ength of messages list != 1") m = c.messages_list[0] Conversation.delete_message(self.u1.username_norm, c.key.id(), m.id()) conv = c.key.get() msg = m.get() self.assertIsNone(conv, "Conversation was not deleted") self.assertIsNone(msg, "Message was not deleted")
def get_files(): user = User.from_json(session['user']) data = request.args parent_id = int(data.get("parentId")) success = False files = [] if user is not None: if parent_id == -1: optional_file = File.get_file(user.get_root_folder_id()) if optional_file is not None: files.append(optional_file) success = True else: files = File.get_children_files(parent_id) success = True files_dict_list = [file.to_dict() for file in files] return jsonify(success=success, data=files_dict_list)
def del_user(self): """ Delete user objects in the database, you cannot delete yourself. """ user = User.by_uuid(self.get_argument("uuid", "")) if user is None: self.render("admin/view/users.html", errors=["User does not exist"]) elif user == self.get_current_user(): self.render("admin/view/users.html", errors=["You cannot delete yourself."]) else: logging.info("Deleted User: '******'" % str(user.handle)) EventManager.instance().deauth(user) self.dbsession.delete(user) self.dbsession.commit() self.event_manager.push_score_update() self.redirect("/admin/users")
def get(self, conv_id=None, msg_id=None): # (conv_id and msg_id) or (not conv_id and not msg_id) if not bool(conv_id) ^ bool(msg_id): username = self.get_cookie("username") show, start, end, thread, id = self.get_params(["show", "from", "to", "thread", "id"]) me = User.get_user(username) friends = me.get_friends() if show in ('all', 'new') or not show: if show == 'new': self.show_form_for_new_message(conv_id, msg_id, friends) elif show == 'all' or not (show or conv_id or msg_id): self.display_messages(username, start, end, friends) elif conv_id and msg_id: self.display_message(int(msg_id), int(conv_id), friends) else: self.response.out.write("invalid url")
def wrapper(*args, **kwargs): token = request.headers.get('Authorization', '').replace('Bearer ', '') try: payload = jwt.decode(token, secret) g.current_user = User.get(id=payload['sub']) except jwt.ExpiredSignatureError: # token has expired return jsonify({'error': 'Session over. Please log in again.'}), 401 except Exception as err: # any other error has occurred print(err) return jsonify({'error': 'Please log in to do this.'}), 401 return func(*args, **kwargs)
def register(): if request.method == 'POST': uname = request.form['username'] pswd = request.form['password'] rpswd = request.form['rpassword'] if pswd == '' or rpswd == '' or pswd != rpswd: return render_template('register.html', err_msg='两次密码不同!') user = User.query.filter_by(username=uname).first() if user is not None: return render_template('register.html', err_msg='用户名已存在!') else: user = User(uname, pswd) db.session.add(user) db.session.commit() return render_template('login.html', err_msg='注册成功!') else: return render_template('register.html')
def update(user_id): schema = UserSchema() user = User.get(id=user_id) if not user: abort(404) try: data = schema.load(request.get_json()) user.set(**data) db.commit() except ValidationError as err: return jsonify({ 'message': 'Validation failed', 'errors': err.messages }), 422 return schema.dumps(user)
async def get_current_user(request: Request, token: str = Depends(oauth2_scheme)): authenticate_value = f"Bearer" credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": authenticate_value}, ) #todo add private key, or public key for token ? try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("sub") if username is None: log.warning("the token is not own by any user") raise credentials_exception tmp_token_scopes = payload.get("scopes", []) # get user acl #for some reason when you encode a list a triple if become a list of list with 3 elt token_scopes = [] try: for elt in tmp_token_scopes: token_scopes.append((elt[0], elt[1], elt[2])) #creating a new list of triples except IndexError: log.warning("A problem occurred when getting the ace from the token") raise credentials_exception token_data = TokenData(scopes=token_scopes, username=username) except (JWTError, ValidationError): raise credentials_exception query = f"""SELECT USER_ID FROM USERS WHERE NAME='{username}';""" if not database.is_connected: await database.connect() res = await database.fetch_one(query=query) if not res[0]: log.warning("the user don't exist in the database") raise credentials_exception if not verify_permission(get_required_scopes_from_endpoint(request), token_data): log.warning("the user don't have enough permission") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Not enough permissions", headers={"WWW-Authenticate": authenticate_value}, ) log.msg("The user is authorized") return User(username=username)
def login(): data = request.form.to_dict() if 'username' not in data or 'password' not in data or data[ 'username'].strip() == '' or data['password'].strip() == '': # return render_template('login.html', error='Please Fill All Fields') return Response(json.dumps({ 'success': False, 'err': 'Incomplete Fields' }), mimetype="application/json", status=200) temp = User.objects(username=data['username']) if len(temp) == 0: # return render_template('login.html', error='The Email is not registered') return Response(json.dumps({ 'success': False, 'err': 'User Does not Exist' }), mimetype="application/json", status=200) temp = temp[0] if bcrypt.checkpw(data['password'].encode('utf-8'), temp.password.encode('utf-8')): expires = datetime.timedelta(days=1) token = create_access_token(identity=temp.username, expires_delta=expires) resp = Response(json.dumps({ 'success': True, 'token': token, 'link': '/dashboard' }), mimetype="application/json", status=200) set_access_cookies(resp, token) return resp # return redirect('/dashboard') else: # return render_template('login.html', error='Password Does not match') return Response(json.dumps({ 'success': False, 'err': 'Password does not match' }), mimetype="application/json", status=200)
def login(): username = request.json.get('username') password = request.json.get('password') user = User.verify_auth_token(username) if not user: # try to authenticate with username/password user = User.query.filter_by(username=username).first() if user: if user.verify_password(password): token = user.generate_auth_token() return jsonify({ "sessionToken": token.decode('ascii'), "duration": SESSION_TOKEN_DURATION, "currentUser": user }) else: return jsonify({"message": "password is incorrect"}), 401 else: return jsonify({"message": "Can not find this username"}), 401
def fill_users(): global users if os.path.isfile(os.path.dirname(__file__) + "/data/users.npy"): users = np.load(os.path.dirname(__file__) + "/data/users.npy") for i, user in enumerate(users): userIndexMap[user.username] = i indexUserMap[i] = user.username else: users = [] for i in range(10): username = "******" + str(i) password = "******" + str(i) full_name = "fullName" + str(i) users.append(User(username, password, full_name)) userIndexMap[username] = i indexUserMap[i] = username np.save(os.path.dirname(__file__) + "/data/users", users)
def testAddNewMessage(self): c = User.add_new_conversation(self.u1.username_norm, self.u2.username_norm, title_plain_text, content_plain_text) m = Conversation.add_new_message(self.u2.username_norm, content_plain_text2, conv_key=c.key) c.put() self.assertEqual( len(c.messages_list), 2, "Length of message list %s != %s" % (len(c.messages_list), 2)) test_cont = (content_plain_text, content_plain_text2) for i, msg in enumerate(c.messages_list): newmsg = msg.get() self.assertEqual(newmsg.content, test_cont[i], "Message Content")
def __init__(self, id=0, image=Image(), classifier=Classifier(), analysis_results=[], user=User()): """Analisys model constructor Args: id: Integer number to identification image: Image object that has been used for this Analysis classifier: Classifier object that has been used for this Analysis analysis_results: A list of AnalysisResult object with all results user: User which perform this analysis """ self.id = id self.image = image self.classifier = classifier self.analysis_results = analysis_results self.user = user
def login(): #Si no hay documento JSON: if not request.is_json: return jsonify({"msg": "Missing JSON in request"}), 400 username = request.json['mail'] password = request.json['password'] #Si no hay usuario/contraseña: if not username: return jsonify({"msg": "Missing username parameter"}), 400 if not password: return jsonify({"msg": "Missing password parameter"}), 400 password = hashing.hash_value(password, salt='abcd') h = User().findLogin(username, password) if h == False: return jsonify({"msg": "Bad username or password"}), 401 else: date = datetime.now() date = date + timedelta(seconds=864000) # Identity can be any data that is json serializable access_token = create_access_token(identity=username) refresh_token = create_refresh_token(identity=username) h = literal_eval(h) _id = h['_id'] name = h['name'] mail = h['mail'] rol = h['rol'] verified = h['verified'] category = h['category'] banner = h['banner'] icon = h['icon'] return jsonify(access_token=access_token, refresh_token=refresh_token, _id=_id, name=name, mail=mail, rol=rol, icon=icon, verified=verified, category=category, banner=banner, exp=date.strftime("%m %d %Y %H:%M:%S GMT+0200")), 200
def signup(): if request.method == 'GET': return render_template('signup.html') email = request.form.get('email') name = request.form.get('name') password = request.form.get('password') user = User.query.filter_by(email=email).first() if user: return redirect(url_for('auth.signup')) new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256')) db.session.add(new_user) db.session.commit() return redirect(url_for('auth.login'))
def post(self, *args, **kwargs): """ Validate user arguments for SWAT request """ target = User.by_uuid(self.get_argument("uuid", "")) if target is not None and not target.is_admin(): if not Swat.user_is_pending( target) and not Swat.user_is_in_progress(target): user = self.get_current_user() if target not in user.team.members: if Swat.get_price(target) <= user.team.money: self.create_swat(user, target) self.redirect("/swat") else: self.render_page("You cannot afford this bribe") else: self.render_page("You cannot SWAT your own team") else: self.render_page("A bribe is already exists for this player") else: self.render_page("Target user does not exist")
def func_wrapper(*args, **kwargs): token = None if "Authorization" in request.headers: try: user = get_user_from_header(request) kwargs["client"] = user kwargs["is_device"] = False return func(*args, **kwargs) except InvalidAuthentication: try: device = get_device_from_header(request) kwargs["client"] = device kwargs["is_device"] = True return func(*args, **kwargs) except InvalidAuthentication as ie: resp = jsonify({"success": False, "message": str(ie)}) resp.status_code = 500 return resp if token is None or token == "": if "neo_user_token" in request.cookies: token = request.headers.get("neo_user_token") res, data = User.decode_auth_token_old(token) if res is True: kwargs['client'] = data kwargs["is_device"] = False return func(*args, **kwargs) else: resp = jsonify({"success": False, "message": data}) resp.status_code = 401 return resp if "neo_device_token" in request.cookies: token = request.headers.get("neo_device_token") res, data = Device.decode_auth_token_old(token) if res is True: kwargs['client'] = data kwargs["is_device"] = True return func(*args, **kwargs) else: resp = jsonify({"success": False, "message": data}) resp.status_code = 401 return resp resp = jsonify({"success": False, "message": "Token introuvable"}) return resp
def post(self): # for i in parser.parse_args(): # print(i) data = request.get_json(force=True) print(data) user = U.objects(username=data['username']).get() if not user: return jsonify({"message": "User does not exist"}) if user and bcrypt.check_password_hash(user.password, data['password']): access_token = create_access_token(identity=data['username']) refresh_token = create_refresh_token(identity=data['username']) return jsonify({ "message": "Logged in as {}".format(user.username), "access_token": access_token, "refresh_token": refresh_token }) else: return jsonify({"message": "Wrong credentials"})
def register(): form = RegisterForm(request.form) if request.method == 'POST' and form.validate(): name = form.name.data email = form.email.data username = form.username.data # TODO password = sha256_crypt.encrypt(str(form.password.data)) user = User(name, email, username, password) if db.register_user(user): flash('You are now registered and can log in', 'success') return redirect(url_for('index_page.index')) else: flash('User already exist!', 'danger') return render_template('register.html', form=form) return render_template('register.html', form=form)
def post(self, *args, **kwargs): ''' Validate user arguments for SWAT request ''' target = User.by_uuid(self.get_argument('uuid', '')) if target is not None and not target.has_permission(ADMIN_PERMISSION): if not Swat.user_is_pending( target) and not Swat.user_is_in_progress(target): user = self.get_current_user() if not target in user.team.members: if Swat.get_price(target) <= user.team.money: self.create_swat(user, target) self.redirect('/swat') else: self.render_page("You cannot afford this bribe") else: self.render_page("You cannot SWAT your own team") else: self.render_page("A bribe is already exists for this player") else: self.render_page("Target user does not exist")
def get(self, user_id): user = User.objets(id=user_id) if not user: return {'error': 'this User not exists!'}, 400 try: task_lists = TaskList.objects(created_by=user) return Response(task_lists, mimetype="application/json", status=200) except (UnauthorizedError, DoesNotExist): raise UnauthorizedError except FieldDoesNotExist: raise FieldDoesNotExist except Exception as err: raise InternalServerError
def login(): data = request.get_json() user = User.get(email=data.get('email')) if not user or not user.is_password_valid(data.get('password')): return jsonify({'message': 'Unauthorized'}), 401 favorites = [ fav['objectNumber'] for fav in FavoriteSchema(many=True).dump(user.favorites) ] return jsonify({ 'message': f'Welcome back {user.username}', 'token': user.generate_token(), 'favorites': favorites })
def get(self): name = self.get_cookie('username') friends = None template_values = {} if name: user = User.get_user(name) if user and Authentication.valid_log_token(user.username_norm, user.log_token): friends = user.get_friends() template_values = { 'title': self.get_title(), 'username': name, 'friends': friends } else: self.redirect('/logout') self.render("index.html", template_values)
async def change_password(req, resp, *, id): # check if token is sent in the request if 'quizz-token' in req.headers: # Check if the user is authenticated if check_token(req.headers['quizz-token'], False, False): if User.objects(id=id): if req.method == 'put' or req.method == 'patch': data = await req.media() user = User.objects.get(id=id) auth_user = User.objects.get(token=req.headers['quizz-token']) # Check if the user is trying to update his password or is an admin if True if auth_user.id == id else True if check_token(req.headers['quizz-token'], True, False) else False: # If the user is an admin, only check if new_password exists. If not, check for old_password and new_password if True if auth_user.admin == True and 'new_password' in data else True if 'old_password' in data and 'new_password' in data else False: # If user is an admin, just pass. If not, check if the password in db is the same as the one sent in the request if auth_user.admin == True or pwd_context.verify(data['old_password'], user.password): # Encrypt the password encrypted_password = pwd_context.hash(data['new_password']) # Create the JWT token from the username and the password token = encrypt(user.username, encrypted_password) user.password = encrypted_password user.token = token.decode('UTF-8') user.save(validate=True) resp.status_code = api.status_codes.HTTP_200 resp.media = {'token': token.decode('UTF-8')} else: resp.status_code = api.status_codes.HTTP_401 resp.media = {'message': 'old password does not match'} else: resp.status_code = api.status_codes.HTTP_401 resp.media = {'message': 'data sent not valid'} else: resp.status_code = api.status_codes.HTTP_403 resp.media = {'message': 'Not an admin'} else: resp.status_code = api.status_codes.HTTP_401 resp.media = {'message': 'This user doesn\'t exist'} else: resp.status_code = api.status_codes.HTTP_403 resp.media = {'message': 'Not authenticated or not authorized'} else: resp.status_code = api.status_codes.HTTP_403 resp.media = {'message': 'auth token not sent in request'}
def edit(request): headers = { 'Content-Type': 'text/html', } uname = current_user(request) u = User.find_by(username=uname) if u is None: return redirect('/login') todo_id = int(request.query.get('id', -1)) t = Todo.find_by(id=todo_id) if t.user_id != u.id: return redirect('/login') body = templates('todo_edit.html', todos=t) body = body.replace('{{todo_id}}', str(t.id)) # print('t.id', t.id) body = body.replace('{{todo_title}}', str(t.title)) header = response_with_headers(headers) r = header + '\r\n' + body return r.encode(encoding='utf-8')