def create_user(organization_id: str) -> Any: form = UserForm(request.form) organization = Organization.query. \ filter(Organization.id == organization_id).first() if request.method == 'POST' and form.validate(): user = User() user.organization_id = organization.id form.populate_obj(user) user.active = True try: db.session.add(user) db.session.commit() except IntegrityError: db.session.rollback() form.email.errors.append('This email is already in use') return render_template('users/users/new.html', form=form, organization=organization) except: db.session.rollback() flash('Error saving user') return render_template('users/users/new.html', form=form, organization=organization) return redirect( url_for('organizations.organization', organization_id=organization.id)) return render_template('users/users/new.html', form=form, organization=organization)
def register(): if request.method == "POST": user_name = request.form.get("username") if not re.match(r"[^@]+@[^@]+\.[^@]+", user_name): return render_template("register.html", error="Invalid email address!") password = request.form.get("password") password2 = request.form.get("password2") if password != password2: return render_template("register.html", error="Password Confirmation Error!") if not validate_password(password): return render_template( "register.html", error="Password length should be between 8 and 30 characters.") next_page = request.form.get("next_page", url_for("home")) captcha_response = request.form.get("g-recaptcha-response") if not validate_captcha(captcha_response): return render_template("register.html", error="Recaptcha Fail") if is_abuse_check(request.remote_addr, prefix="register", threshold=10): return render_template("register.html", error="Abuse detected by your IP address.") try: User.add_user(email=user_name, password=password) except Exception as ex: logger.exception(ex) return render_template("register.html", error="Register Fail!") user = web_login(user_name, password) if not user: return render_template("register.html", error="Register Fail!") flash('Check your email to activate account.') return redirect(next_page) else: return render_template("register.html", error=None)
def get_new_board(difficulty): try: payload = verify_decode_jwt(get_token_auth_header()) # Check if the user (auth_id) already exists user = None user_info = payload["http://www.jordanhuus.com/user_info"] if User.query.filter(User.auth_id == payload["sub"]).count() > 0: user = User.query.filter(User.auth_id == payload["sub"]) \ .first() else: first_name = user_info["name"].split(" ")[0] last_name = first_name if len(user_info["name"].split(" ")) \ == 1 else user_info["name"].split(" ")[1] user = User(first_name, last_name, user_info["id"]) user.add() # Store the newly created board board = SudokuBoard(difficulty, user) board.add() except KeyError as ke: abort(400, f"Request body is missing {ke} dictionary key.") except Exception: abort(500) return jsonify(board.format()), 200
def app(): "Initialize the app in test mode, initialises the DB, and adds some test cases" app = create_app('test') with app.test_request_context(): db.create_all() # create a user user = User('default', '*****@*****.**', 'password') db.session.add(user) db.session.flush() # create a new group test_group = Group('TestGroup', user) db.session.add(test_group) db.session.flush() # add an issue to the group issue = Issue('REF', 'Description', test_group.id) db.session.add(issue) # Make the user a member of the group membership = Membership(test_group, user) db.session.add(membership) existing_group = Group('GroupAlreadyExists', user) db.session.add(existing_group) # Second user user = User('bob', '*****@*****.**', 'password') db.session.add(user) db.session.commit() return app
def post(self): form = LoginForm(request.form) if form.validate(): username = request.form.get('username') password = request.form.get('password') try: User.try_login(username, password) except Exception as e: flash('Invalid username or password. Please try again.', 'danger') return render_template('login.html', form=form) user = User.query.filter_by(username=username).first() if not user: user = User(username, password) db.session.add(user) db.session.commit() login_user(user) flash('You have successfully logged in.', 'success') return redirect(url_for('auth.home')) if form.errors: flash(form.errors, 'danger') return render_template('login.html', form=form)
def delete_user(id): try: User.objects.get(user_id=id).delete() User.objects(parent=id).delete() return "User and associate childs are deleted", 200 except: return {"error": "Could not delete user"}, 400
def main(): print('Starting script...') client = ApiHandler(API_ID, API_HASH) print('Auth - successfully!') messages = Message.select() print('Getting messages...\nGot {} messages'.format(len(messages))) user_ids = [] for message in messages: if message.from_id and message.from_id not in user_ids: try: user_ids.append(message.from_id) except Exception: pass print('Got {} unique users'.format(len(user_ids))) users = client.get_users(user_ids) for user in users: User.get_or_create(user_id=user['id'], username=user['username'], first_name=user['first_name'], last_name=user['last_name']) print('Done!')
def get(self): # Get current requesting user user_id = get_jwt_identity() current_user = User.objects(id=user_id).first() if current_user is None: return {'error': 'Header token is not good, please login again'}, 401 all_users = User.objects(id__ne=user_id).to_json() all_users = json.loads(all_users) c = 0 for u in all_users: u['already_follow'] = False for user in u['followers']: if user['$oid'] == user_id: u['already_follow'] = True break del u['password'] del u['image_queue'] del u['pictures'] del u['followers'] del u['following'] del u['nb_followers'] del u['nb_following'] del u['dates'] del u['nb_login'] all_users[c] = u c += 1 return Response(json.dumps(all_users), mimetype="application/json", status=200)
def setUpClass(self): self.connection = connect(db='mongoenginetest', host='mongomock://localhost') self.user_id = '1088308123' user = User(user_id=self.user_id, pin='12345') user.save()
def deposit_money(self, user_id, money, **kwargs): """Realiza un depósito de dinero en la cuenta del usuario solicitado.""" if money >= 0: print('Cantidad depositada: ', money) User.objects(user_id=user_id).update_one(inc__balance=money) else: print('No es posible depositar valores negativos.')
def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() import database.models if get_config()['mode'] == 'dev': Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) from database.models import User admin = User( civilite='M', firstName='admin', lastName='nimda', birthDate='2019-01-01', phone='0658062948', email='*****@*****.**', pwd='jdida', plastaId='a111111', surveyId='40340304', verified=True, blocked=False, fixedOldJobValue=False, fixedAlphaBeta=False, group='J4UINT_C1NE') other = User( civilite='M', firstName='other', lastName='nimda', birthDate='2019-01-01', phone='0658062947', email='*****@*****.**', pwd='jdida', plastaId='009', surveyId='40340304', verified=True, blocked=False, group='CGTINT_C1NE') ather = User( civilite='M', firstName='ather', lastName='nimda', birthDate='2019-01-01', phone='0658062949', email='*****@*****.**', pwd='jdida', plastaId='003', surveyId='9021988', verified=True, group='ather-ather') try: db_session.add_all([admin, other, ather]) db_session.commit() print(User.query.all()) except: print('Fake users already populated')
def create_user(user: schemas.security.UserCreate, db: Session = Depends(get_db)): db_user = User.by_email(user.email, db) if db_user: raise HTTPException(status_code=400, detail='Email already registered') # Overwrite user.password with a hashed version user.password = get_password_hash(user.password) return User.create(user, db)
def post(self): body = request.get_json() user = User(**body) try: user.save() except NotUniqueError: raise EmailAlreadyExist return user_schema.dump(user, many=False).data, 201
def test_user(self): User.add_user("*****@*****.**", "any") our_item = self.session.query(User).filter_by( email='*****@*****.**').first() usr = UserCH(our_item.id) self.assertEqual(usr.email, "*****@*****.**") self.assertEqual( cache.get_object("cached/{}/{}".format(usr.db_table, usr.id)), usr._data)
def userTestData(): newUser = User(id = 1, email = "*****@*****.**", username = "******", password = "******", company_name = "Fence", active = True) newUser1 = User(id = 2, email = "*****@*****.**", username = "******", password = "******", company_name = "Builder", active = True) newUser2 = User(id = 3, email = "*****@*****.**", username = "******", password = "******", company_name = "Fence", active = False) newUser3 = User(id = 4, email = "*****@*****.**", username = "******", password = "******", company_name = "Builder", active = False) dbSession.add(newUser) dbSession.add(newUser1) dbSession.add(newUser2) dbSession.add(newUser3) dbSession.commit()
async def get(username: str, fetch_password: bool = False) -> User_Pydantic: try: if fetch_password: user = await UserIn_Pydantic.from_queryset_single(User.get(username=username)) else: user = await User_Pydantic.from_queryset_single(User.get(username=username)) return user except DoesNotExist: raise NotImplementedException
def create_user(data): name = data.get('name') user_id = data.get('id') email = data.get('email') user = User(name, email) if user_id: user.id = user_id db.session.add(user) db.session.commit()
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def all_users(request): if request.method == 'GET': all_users = User.objects.all().values('username', 'first_name', 'last_name') return JsonResponse({'users': list(all_users)}, status=200) else: fields = json.loads(request.body.decode('utf-8')) # fields['username'] = request.user.user_name fields['username'] = '******' current_user = User(**fields) current_user.save() return JsonResponse({"status": "resource created"}, status=200)
def post(self, current_user): parser = reqparse.RequestParser(bundle_errors=True) parser.add_argument('content', type=str, required=True, help="Content cannot be blank!", location='json') args = parser.parse_args() newPost = User(public_post_id=str(uuid.uuid4()), content=args['content'], public_user_id=current_user.public_user_id) newPost.save() return {'success': True, 'message': 'Post created'}, 204
def setUp(self): app.config.update({ "TESTING": True, "TEMP_DB": True, "WTF_CSRF_ENABLED": False, "DEBUG": False }) self.app = app.test_client() self.assertEqual(app.debug, False) db.disconnect() db.connect('sample_test') User.drop_collection() app.register_blueprint(auth_api, url_prefix='/api/auth')
def sign_up(): if current_user.is_authenticated: return redirect(url_for('ui.prices')) form = SignUpForm(meta={'csrf': False}) if form.validate_on_submit(): user = User(username=form.username.data) user.set_password(form.password.data) with session_scope() as session: session.add(user) session.commit() flash("Registration successful. Please, sign in now.") return redirect(url_for('auth.sign_in')) return render_template('auth/register.html', form=form)
def post(self): try: body = request.get_json() user = User(**body) user.save() return 'User Registered sucessfully', 200 except FieldDoesNotExist: raise SchemaValidationError except ValidationError: raise SchemaValidationError except NotUniqueError: raise UserNameAlreadyExistsError except Exception as e: raise InternalServerError
async def signup(form_data: EmailPasswordForm, request: Request, background_tasks: BackgroundTasks): try: try: user = User(email=form_data.username, password=form_data.password) except NotUniqueError: user = User.objects.get(email=form_data.username, verified=False, created__lt=datetime.now() - timedelta(days=1)) user.password = form_data.password if User.objects.count() == 0: user.admin = True user.hash_password() user.save() verify_token = create_access_token(str(user.id), expires_delta=timedelta(days=1)) send_email_backround( background_tasks, 'Verify Your Email', [user.email], 'verify_email.html', { 'url': f'{request.client.host}:{request.client.port}/login?t={verify_token}', }) # FOR DEBUG PURPOSES # TODO: remove in production print(request.client.host + ':' + request.client.port + '/login?t=' + verify_token) return {'id': str(user.id)} except DoesNotExist: raise UserAlreadyExistsError().http_exception except Exception as e: raise e
def insertUsername(mac_address, username): #username is invalid if (username == None): return -1 #mac address exists if (getSystemInformation(mac_address) != None): for x in getUsernames(mac_address): #registry already exists if x[1] == username: return -1 #registry does not exist, add it sys_info = System_Information.objects.get(mac_address=mac_address) obj = User(mac_address=sys_info, username=username) obj.save()
def edit_conversiton(): # get user data from the body as json. userData = request.json userId = userData['id'] userName = userData['name'] userAvatar = userData['avatar'] try: User.objects(userId=userId).update(name=userName, avatar=userAvatar) return {"success": True, "msg": "User Updated.."} except Exception as e: return {"success": False, "msg": "Something Wron.."} print("update user info something wrong, ", e)
def get(self): u = User.objects(role__nin=['user']).\ exclude('private_key', 'public_key', 'password') if 'unapproved' in request.args: u = User.objects(Q(role=get_jwt_identity()['role']) & Q(approved=False)).\ exclude('private_key', 'public_key', 'password') if 'excel' in request.args: return send_from_directory(directory=UPLOAD_FOLDER, filename=export_to_excel( u, get_user_id())) return Response(u.to_json(), mimetype="application/json", status=200)
def get(self, id): try: item = Product.objects().get(id=id).to_json() except DoesNotExist: return {'error': 'Product ID not found'}, 404 else: if get_jwt_identity(): user_id=get_jwt_identity() if User.objects(id=user_id,recently_viewed=id): User.objects(id=user_id).update_one(pull__recently_viewed=id) User.objects(id=user_id).update_one(push__recently_viewed=id) # print(User.objects(id=user_id)[0].recently_viewed) return Response(item, mimetype="application/json", status=200)
def signup(request): # 실제 데이터베이스에 데이터를 저장(회원가입) if request.method == 'POST': # 회원정보 저장 email = request.POST.get('email') name = request.POST.get('name') pwd = request.POST.get('pwd') user = User(email=email, name=name, pwd=pwd) user.save() return HttpResponseRedirect('/main/') # 화원가입을 위한 양식 전송 return render(request, 'signup.html')
def sign_up(): if current_user.is_authenticated: return redirect(url_for('index.index')) form = SignupForm() if not form.validate_on_submit(): return render_template('user/signup.html', title=_('Register'), form=form) user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) flash(_('Congratulations, you are now a registered user!')) return redirect(url_for('user_bp.signin'))
def login_result(request): # 登陆的结果 password = request.POST['password'] if password=='': return HttpResponse('登陆失败!请填写密码') email = request.POST['email'] if email=='': return HttpResponse('登陆失败!请填写邮箱') u=User() u.email=email u.password=password try: user=User.objects.get(email=email) # user是指从数据库里面查找的邮箱为email的用户 except User.DoesNotExist: return HttpResponse("账户不存在") if user.password==hashlib.sha1(u.password).hexdigest(): # u是登陆之时填写的用户 result=get_template('login_result.html') # 比较数据库的用户的密码和填写的密码是否一致 resultHtml=result.render(Context()) request.session['user']=user return HttpResponse(resultHtml) else: return HttpResponse("密码错误")
def _check_token(): """Custom user auth by token.""" request_token_header = getattr(config, 'SECURITY_TOKEN_AUTHENTICATION_HEADER', 'Token') token = flask.request.headers.get(request_token_header, None) if token is not None: user = User.get_user_by_token(token) return user if user is not None else False return False
def post(self): """Register method.""" register_data = flask.request.json data_checked = self._check_register_data(register_data) if data_checked is True: user = User.create(**register_data) user.commit() return flask.jsonify({'token': user.token}) return flask.jsonify({'message': 'Wrong register data. {}' .format(data_checked)})
def auth_login(): error_message = [] user_name = request.forms.get('user_name') input_password = request.forms.get('password') u = User.get_by_name(user_name) # O utilizador nao existe? if u is None: error_message.append('O utilizador nao existe') return jresp.reply( payload=None, success=False, error_message=error_message ) else: db_password = u['password'] # Validar palavra-passe if not auth.password_matches(input_password, db_password): error_message.append('A password esta incorrecta') return jresp.reply( payload=None, success=False, error_message=error_message ) # User existe e password esta correcta: # criar e gravar token de sessao # enviar mensagem com o token de sessao new_session_token = auth.generate_session_token() new_session = UserSession( user_id=u['id'], token=new_session_token ) new_session.save() # Tudo correu bem: payload = { 'token': new_session_token } return jresp.reply( payload=payload, error_message=None, success=True )
def check_token(): token = request.forms.get('token') if UserSession.token_exists(token): user_id = UserSession.get_user_id_by_token(token) user = User.get_by_id(user_id) payload = { 'message': 'A sessao encontra-se activa.', 'user': { 'name': user.name, } } return jresp.reply( payload=payload, ) else: error_message = [['A sessao nao esta activa']] return jresp.reply( payload=None, success=False, error_message=error_message )
def reg_result(request): # 注册的结果页面 password = request.POST['password'] #从表单里拿到密码 if password=='': # 没填密码 return HttpResponse('注册失败!请填写密码') email = request.POST['email'] if email=='':# 没填邮箱 return HttpResponse('注册失败!请填写邮箱') realname = request.POST['realname'] if realname=='': return HttpResponse('注册失败!请填写真实姓名') invitecode = request.POST['invitecode'] if invitecode=='': return HttpResponse('注册失败!请填写邀请码') u=User() # 新建一个User对象,把它存入数据库 u.email=email u.password=hashlib.sha1(password).hexdigest() # 这是生成hash值代替明文的密码 u.name=realname u.sec=Section.objects.get(id=1) u.save() request.session['user']=u # 把user对象放到session里面去 result=get_template('result.html') resultHtml=result.render(Context()) return HttpResponse(resultHtml)
def reg_result(request): # 注册的结果页面 u=User() # 新建一个User对象,把它存入数据库 password = request.POST['password'] #从表单里拿到密码 if password=='': # 没填密码 return HttpResponse('注册失败!请填写密码') email = request.POST['email'] if email=='':# 没填邮箱 return HttpResponse('注册失败!请填写邮箱') name = request.POST['name'] if name=='': return HttpResponse('注册失败!请填写真实姓名') invitecode = request.POST['invitecode'] if invitecode=='': return HttpResponse('注册失败!请填写邀请码') sec = request.POST['sec'] if sec==u'主席团': u.sec=Section.objects.get(id=2) if sec==u'技术部': u.sec=Section.objects.get(id=1) if sec==u'运营部': u.sec=Section.objects.get(id=3) if sec==u'宣传部': u.sec=Section.objects.get(id=4) if sec==u'财务部': u.sec=Section.objects.get(id=5) college = request.POST['college'] major = request.POST['major'] entry_year = request.POST['entry_year'] grade = request.POST['grade'] campus = request.POST['campus'] sex = request.POST['sex'] phone = request.POST['phone'] province = request.POST['province'] city = request.POST['city'] area = request.POST['area'] qq = request.POST['qq'] love = request.POST['love'] #city = request.POST['city'] u.school='南开大学' u.email=email u.password=hashlib.sha1(password).hexdigest() # 这是生成hash值代替明文的密码 u.name=name u.college=college u.major=major u.entry_year=entry_year u.grade=grade u.campus=campus u.sex=sex u.phone=phone u.province=province u.city=city u.area=area u.qq=qq u.love=love u.effective=1 u.authority=0 try: # 测试邮箱是否已经被使用过了 User.objects.get(email = email) except User.DoesNotExist: pass else: return HttpResponse("该邮箱已被注册,请您换一个未被注册过的有效邮箱进行注册!") try: c=Code.objects.get(code=invitecode) if c.effective==0: return HttpResponse("该邀请码已经被使用过了!请确认您拥有正确的邀请码!") else: u.save() c.effective=0 c.use =User.objects.get(email = email) # 把验证码和用户关联上 c.save() except Code.DoesNotExist: return HttpResponse("该邀请码不存在!请确认您拥有正确的邀请码!") request.session['user']=u # 把user对象放到session里面去 result=get_template('result.html') resultHtml=result.render(Context()) return HttpResponse(resultHtml)
from database.models import User u = User.get_by_name('kjhgf') print(u)
def create_account(): error_message = [] name = request.forms.get('name', '') password = request.forms.get('password', '') password_confirmation = request.forms.get('password_confirmation', '') email = request.forms.get('email', '') # Validaçao: if name == '': error_message.append('O nome de Utilizador esta vazio') if password == '': error_message.append('O campo password esta vazio') if password is not None and len(password) > 6: error_message.append('A password tem de ter pelo menos 6 caracteres') if password_confirmation == '': error_message.append('O campo confirmaçao de password esta vazio') if password != password_confirmation: error_message.append('As passwords nao sao iguais') # http://stackoverflow.com/questions/8022530/ # python-check-for-valid-email-address/8022584#8022584 if not re.match(r"[^@]+@[^@]+\.[^@]+", email): error_message.append('O endereço de email nao e valido') # Ja existe algum utilizador na base de dados com este nome? if name != '': u = User.get_by_name(name) if u is not None: error_message.append('O nome de utilizador ja existe') # Ja existe algum utilizador na base de dados com este Email? if email != '': u = User.get_by_email(email) if u is not None: error_message.append('O email ja existe') # Alguma das Validaç~oes devolveu erro? if len(error_message) > 0: return jresp.reply( payload=None, success=False, error_message=error_message ) else: # 1->Inserir o novo utilizador # 2->Enviar o email plaintext_password = password hashed_password = auth.hash_password(plaintext_password) try: user = User(name=name, email=email, password=hashed_password) user.save() except: error_message.append('Erro ao comunicar com a base de dados!') return jresp.reply( response=response, payload=None, success=False, error_message=error_message, status=500 ) ''' from services import mailgun as mail try: mail.send(template='account_confirmation', name=name, email=email) except: error_message.append('Erro ao enviar email!') return jresp.reply( response=response, payload=None, success=False, error_message=error_message ) ''' # Tudo correu bem: payload = [{ 'message': 'Conta de utilizador criada com sucesso.' }] return jresp.reply( payload=payload, )