def registration(self): if not request.is_json: return jsonify({"msg": "Missing JSON in request"}), 400 username = request.json.get('username', None) #TODO: hash the password password = request.json.get('password') first_name = request.json.get('first_name') last_name = request.json.get('last_name') email = request.json.get('email') national_id = request.json.get('national_id') classes = [] students = [] exams = [] account_activated = True # roles = [Role('holder')] session = db_session() try: user = User(first_name, last_name, email, national_id, username, password, account_activated, classes, students, exams) session.add(user) session.commit() #TODO: redirect and provide JWT token and return it return jsonify(success=True), 201 except Exception as e: session.rollback() Logger.debug("registration: Could not add new user to database") Logger.error(e.message) return jsonify(success=False), 400
def login(): response = dict() email = request.json.get('email') password = request.json.get('password') user = User.find_one({'email': email, 'enabled': True}) if user.verify_password(password): # Creates session and persists it in Redis access_token = create_access_token(user.id) refresh_token = create_refresh_token(user.id) access_jti = get_jti(encoded_token=access_token) refresh_jti = get_jti(encoded_token=refresh_token) redis.set(access_jti, 'false', ConfigJWT.JWT_ACCESS_TOKEN_EXPIRES * 1.2) redis.set(refresh_jti, 'false', ConfigJWT.JWT_REFRESH_TOKEN_EXPIRES * 1.2) response['access_token'] = access_token response['refresh_token'] = refresh_token response['expires_in'] = datetime.now( ) + ConfigJWT.JWT_ACCESS_TOKEN_EXPIRES code = 201 else: response['message'] = 'unauthorized' code = 401 return response, code
def delete(): current_user = User.find_one({'id': session.get('user_id')}) current_user.soft_delete() session.clear() db.session.commit() flash('Yout account has been delete', 'info') return redirect(url_for('home.list_publish_articles'))
def update_details(): current_user = User.find_one({'id': session.get('user_id')}) if request.method == 'POST': email = request.form.get("email") first_name = request.form.get("first_name") last_name = request.form.get("last_name") if email == current_user.email or User.is_email_available(email): current_user.first_name = first_name current_user.last_name = last_name current_user.email = email current_user.update() session['user_name'] = first_name db.session.commit() return redirect(url_for('profile.details')) else: flash('Email is not available', 'error') return render_template('profile/edit.html', current_user=current_user)
def register_user(): # Gets params email = request.json.get('email') password = request.json.get('password') password_confirm = request.json.get('password_confirm') first_name = request.json.get('first_name') last_name = request.json.get('last_name') # Checks password if password != password_confirm: abort(409, Response('Passwords do not match')) # Checks integrity user_to_check = User.find_one({'email': email, 'enabled': True}) if user_to_check is None: # Creates user user = User(email=email, first_name=first_name, last_name=last_name) user.hash_password(password) user.create() # Persists it db.session.commit() message = user_schema.dump(user) code = 200 else: message = '{} email is not available'.format(email) code = 409 return message, code
def register(): if request.method == 'POST': # Get params email = request.form.get('email') password = request.form.get('password') password_confirm = request.form.get('password_confirm') first_name = request.form.get('first_name') last_name = request.form.get('last_name') # Check password if password != password_confirm: flash('Password does not match', 'danger') return render_template('user/register.html') # Checks integrity if User.find_one({'email': email, 'enabled': True}) is None: # Creates user user = User(email=email, first_name=first_name, last_name=last_name) user.hash_password(password) user.create() # Persists it db.session.commit() else: flash('The email is not available', 'danger') return render_template('user/register.html')
def update_profile(): current_user = User.find_one({'id': get_jwt_identity()}) current_user.email = request.get_json().get('email', current_user.email) current_user.first_name = request.get_json().get('first_name', current_user.first_name) current_user.last_name = request.get_json().get('last_name', current_user.last_name) current_user.update() return user_schema.dump(current_user), 200
def delete_profile(): current_user = User.find_one({'id': get_jwt_identity()}) if current_user.verify_password(request.get_json().get('password')): # TODO: Remove tokens in redis current_user.soft_delete() message = 'ok' code = 200 else: message = 'password incorrect' code = 401 return message, code
def update_password(): current_user = User.find_one({'id': get_jwt_identity()}) if request.get_json().get('password') == request.get_json().get('password_confirm'): current_user.hash_password(request.get_json().get('password')) current_user.update() message = 'ok' code = 200 else: message = 'password does not match' code = 409 return message, code
def update_password(): if request.method == 'POST': if request.form.get("password") == request.form.get("password_confirm"): current_user = User.find_one({'id': session.get('user_id')}) current_user.hash_password(request.form.get("password")) current_user.update() db.session.commit() flash('Password updated', 'error') return redirect(url_for('profile.details')) else: flash('Password does not match', 'error') return redirect(url_for('profile.update_password')) return render_template('profile/edit_password.html')
def search(self, count, city, sex, age_from, age_to, offset=None, status=None, birth_day=None, birth_month=None): """ Возвращает список пользователей в соответствии с заданным критерием поиска. После успешного выполнения возвращает объект, содержащий число результатов в поле count и массив объектов, описывающих пользователей в поле items. Параметры: https://vk.com/dev/users.search :return (list<user>) """ url = '{api}users.search'.format(api=self.api_url) params = { 'city': city, 'sort': '0', 'offset': offset, 'count': count, 'fields': 'can_write_private_message, last_seen, has_photo, photo_id, blacklisted, friend_status', 'sex': sex, 'status': status, 'age_from': age_from, 'age_to': age_to, 'birth_day': birth_day, 'birth_month': birth_month, 'access_token': self.token, 'v': self.api_version } res = HttpLib(url=url, params=params).send_get() status_code = res.response.status_code assert status_code == status_code_200, '"Users.search" FAILED. {text}'.format( text=res.response.text) response = get_value_from_json(res.response.json(), 'response') users_list = get_value_from_json(response, 'items') user_model_list = [] for user in users_list: if not (UsersApi.is_blacklisted(user)) and (user['id'] not in [ 11225104, 150437158 ]): user_model = User(user) user_model_list.append(user_model) self.logger.log_info(u'Всего найдено пользователей: {count}.'.format( count=len(user_model_list))) return user_model_list
def get(self, user_id): url = '{api}users.get'.format(api=self.api_url) params = { 'user_ids': user_id, 'fields': 'can_write_private_message, last_seen, has_photo, photo_id, blacklisted, friend_status', 'access_token': self.token, 'v': self.api_version } res = HttpLib(url=url, params=params).send_get() status_code = res.response.status_code assert status_code == status_code_200, '"Users.get" FAILED. {text}'.format( text=res.response.text) response = get_value_from_json(res.response.json(), 'response')[0] if get_value_from_json(response, 'blacklisted') == 0: return User(response)
def login(): form = LoginForm() if form.validate_on_submit(): login = form.login.data password = form.password.data user = model.getUserByLoginAndPassword(login, password) if user is not None: g.user = User(user['userID'], user['login'], user['password']) login_user(g.user) flash(u'Bienvenue {0}'.format(login)) return redirect(url_for('index')) else: flash(u'Nom d\'utilisateur invalide') return redirect(url_for('login')) return render_template('login.html', form=form)
def unfollow_product(product_id): current_user = User.find_one({'id': get_jwt_identity()}) relation = UserToProduct.find_one({ 'product_id': product_id, 'user_id': current_user.id }) if relation is not None: relation.delete() db.session.commit() message = 'ok' code = 200 else: message = 'not found' code = 404 return message, code
def follow_product(): current_user = User.find_one({'id': get_jwt_identity()}) url = request.get_json().get('url') trigger = request.get_json().get('trigger', -1) # Check product product = Product.find_one({'url': url}) if product is None: name, current_price = Product.extract_data(url) product = Product(name=name, price=current_price, url=url) product.create() # Create relationship current_user.follow_product(product_id=product.id, difference_trigger=trigger) db.session.commit() return product_schema.dump(product), 200
def login(): next_url = request.args.get('next') or request.form.get('next') if request.method == 'POST' and request.form.get( 'email') and request.form.get('password'): email = request.form.get('email') password = request.form.get('password') user = User.find_one({'email': email, 'enabled': True}) if user is not None and user.verify_password(password): session['logged_in'] = True session['user_id'] = user.id session['user_name'] = user.first_name session.permanent = True # TODO: Use cookie to store session. # session.set_cookie('user_id', user.id) session['is_admin'] = user.is_admin() flash('You are now logged in.', 'success') return redirect(next_url or url_for('home.list_publish_articles')) else: flash('Incorrect email or password.', 'danger') return render_template('auth/login.html', next_url=next_url)
def setUserInfo(): userName = request.form['userName'] email = request.form['email'] if len(userName) < 2 or len(userName) > 20: flash(u"请输入2-20个字符的用户名!") return redirect(url_for('admin.userInfo')) if not reEmail(email): flash(u"邮箱【%s】格式不对,请重新输入!" % email) return redirect(url_for('admin.userInfo')) if current_user.userName != userName: if User.objects(userName=userName).first(): flash(u"用户名【%s】已经存在,请重新输入!" % userName) return redirect(url_for('admin.userInfo')) current_user.userName = userName current_user.email = email current_user.save() flash(u"信息修改成功!") return redirect(url_for('admin.userInfo'))
def get(self, user_id=None): """ """ url = '{api}friends.get'.format(api=api_url) params = { 'user_id': user_id, 'fields': 'has_photo, photo_id, can_write_private_message, last_seen', 'access_token': self.token, 'v': api_version } res = HttpLib(url=url, params=params).send_get() status_code = res.response.status_code assert status_code == status_code_200, '"Friends.add" FAILED. {text}'.format( text=res.response.text) response = get_value_from_json(res.response.json(), 'response') friends_list = get_value_from_json(response, 'items') friends_model_list = [] for friend in friends_list: friend_model = User(friend) friends_model_list.append(friend_model) return friends_model_list
def load_user(id): return User.objects(id=id).first()
def retrieve_profile(): return user_schema.dump(User.find_one({'id': get_jwt_identity()})), 200
def list_all(): return render_template('user/management.html', users=User.find_all())
def details(): return render_template('profile/details.html', current_user=User.find_one({'id': session.get('user_id')}))
def delete(user_id): user = User.find_one({'id': user_id}) user.soft_delete() db.session.commit() return '', 204
def restore(user_id): user = User.find_one({'id': user_id}) user.restore() db.session.commit() return 200
def user_loader(user_id): user = model.getUserById(user_id) if user is not None: g.user = User(user['userID'], user['login'], user['password']) return g.user return None