def add_user_in_db(session_id, username, game, field, status=0, status_first=1): """create user in database for registration in game Arguments: - `session`: uniq session - `user`: name user from form - `game`: id game - `field`: id fields - `status`: status of user on site """ # check session_id in database users = Users.objects(session=session_id) if not users: new_user = Users(user_name=username, session=session_id, game=game, field_battle=field, status=status, status_first=status_first) new_user.save() else: user = Users.objects.get(session=session_id) user.game = game user.user_name = username user.field_battle = field user.status = status user.status_first = status_first user.last_time = datetime.datetime.now() user.save() game.time_begin = datetime.datetime.now() game.time_end = datetime.datetime.now() game.save() return True
def facebook_authorized(resp): next_url = request.args.get('next') or url_for('index') if resp is None: flash('You denied the login') return redirect(next_url) session['fb_access_token'] = (resp['access_token'], '') me = facebook.get('/me') user = Users.query.filter_by(fb_id=me.data['id']).first() if user is None: fb_id = me.data['id'] if me.data['username']: fb_username = me.data['username'] else: fb_username = me.data['name'] fb_email = me.data['email'] user = Users(fb_username, 'temp',fb_email) user.fb_id = me.data['id'] user.activate = True user.created = datetime.utcnow() db.session.add(user) db.session.commit() session['user_id'] = user.uid flash('You are now logged in as %s' % user.username) return redirect(url_for('index'))
def check(request): searchInput = request.POST.get('searchInput') if searchInput is not '': users = Users.objects.filter(username=searchInput) if len(users) > 0: user_id = users[0].userId # is working return HttpResponseRedirect(reverse('photos:view1', kwargs={'userId': user_id})) else: r = requests.get('https://api.instagram.com/v1/users/search?access_token=1497402817.1fb234f.1b8969bb3b304945a6782ae574069017&q={}'.format(searchInput)) response = r.json() for user in response['data']: if user['username'] == searchInput and len(user['username']) == len(searchInput): userId = user['id'] username = user['username'] newUser = Users(userId = userId, username=username) newUser.save() return HttpResponseRedirect(reverse('photos:view1', kwargs={'userId': userId})) return render(request, 'photos/search.html', { 'error_message': "Please input a valid username.", })
def create(request): if request.method=='POST': name = request.POST['username'] email = request.POST['email'] sex = request.POST['sex'] mobile_number = request.POST['mobile_number'] exam_city = request.POST['exam_city'] current_city = request.POST['current_city'] exam_date = request.POST['exam_date'] if exam_date == '' or name == '' or email == '' or mobile_number == '' : return render_to_response('share/create.html') else : new_obj = Users(name = name, email = email, sex = sex, mobile_number = mobile_number,exam_city_id = exam_city,exam_date = exam_date, current_city = current_city) new_obj.save() if "requested_to" in request.session: obj = Request(requester = new_obj.id,requested_to = request.session["requested_to"]) obj.save() del request.session["requested_to"] return HttpResponseRedirect('/thanks/') return HttpResponseRedirect('/thankyou/') if "exam_city" in request.session: return render_to_response('share/create.html',{'exists':1,'exam_date':request.session["exam_date"]}) return render_to_response('share/create.html',{'exists':0})
def facebook_authorized(resp): next_url = request.args.get("next") or url_for("index") if resp is None: flash("You denied the facebook login") return redirect(next_url) session["fb_access_token"] = (resp["access_token"], "") me = facebook.get("/me") user = Users.query.filter_by(fb_id=me.data["id"]).first() if user: if me.data["username"]: fb_username = me.data["username"] else: fb_username = me.data["name"] fb_email = me.data["email"] role = 1 user = Users(fb_username, "temp", fb_email, role) user.fb_id = me.data["id"] user.activate = True user.created = datetime.utcnow() db.session.add(user) db.session.commit() session["user_id"] = user.uid flash("You are now logged in as %s" % user.username) return redirect(url_for("index"))
def facebook_user_query( field, datastore_key, user=None, google_token=None, facebook_token=None, default=None, force_update=False, format_f=lambda x: x, ): """This does the work for functions like check_locale and check_timezone. It's a common pattern to query Facebook for 1 piece of info if it's not already in the database, update it if different and then return the result.""" # First find the user if not user: if google_token: user = Users.all().filter("google_token = ", google_token).get() elif facebook_token: user = Users.all().filter("facebook_token = ", facebook_token).get() # Next check the existing data if user and not force_update: existing = getattr(user, datastore_key) # Todo - more useful check for existing being OK if existing != None: return format_f(existing), False # No good, ask Facebook graph = facebook.GraphAPI(facebook_token or (user and user.facebook_token)) try: results = graph.get_object("me", fields=field) except GraphAPIError, err: return None, parse_facebook_error(err)
def get_user(user): """ Get a user from the datastore """ user_db = Users.get_by_id(user.user_id()) if user_db is None: user_db = Users(id=user.user_id(),email=user.email()) user_db.put() return user_db
def registreer(request): #user = Users(Voornaam='', Achternaam='', Email='', Wachtwoord='', Rechten='0') #user.save() if request.method == 'POST': # create a form instance and populate it with data from the request: formregistreer = Registreer(request.POST) # check whether it's valid: if formregistreer.is_valid(): voornaam = formregistreer.cleaned_data['voornaam'] achternaam = formregistreer.cleaned_data['achternaam'] email = formregistreer.cleaned_data['email'] wachtwoord = formregistreer.cleaned_data['wachtwoord'] try: selectedEerder=Users.objects.get(Email=email) formregistreer.errors[""] = ErrorList([u"Het opgegeven email adres is al geregistreerd!"]) except Users.DoesNotExist: if(formregistreer.cleaned_data['wachtwoord'] == formregistreer.cleaned_data['Herhaal_wachtwoord']): voeg_toe = Users(Voornaam=voornaam, Achternaam=achternaam, Email=email, Wachtwoord=wachtwoord, Rechten='0') voeg_toe.save() return HttpResponseRedirect('/login/') else: formregistreer.errors[""] = ErrorList([u"De opgegeven wachtwoorden komen niet overeen!"]) else: formregistreer = Registreer() return render_to_response('registreer.html',{'registreer': formregistreer}, context_instance=RequestContext(request))
def register(request): if request.method == "POST": first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] password = request.POST['password1'] c_password = request.POST['password2'] if Users.objects.filter(email=email): messages.error(request, "Ruh Roh! Email is already in use.") return redirect(reverse('main')) result = Users.objects.register(first_name = first_name, last_name =last_name, email=email, password1=password, password2 = c_password) if result[0]: print "No Pass! {}".format(result[1]) for row in result[1]: messages.error(request, row) return redirect(reverse('main')) else: hashed = Users.objects.create_password(password) user = Users(first_name = first_name, last_name = last_name, email= email, password = hashed) user.save() try: u = Users.objects.get(email=email) except: return HttpResponse("Ruh Roh! Something went wrong.v Please contact site administrator.") request.session['first_name'] = u.first_name request.session['uid'] = u.id messages.success(request,"Successfully registered! (or logged in)") return redirect(reverse('success')) else: return redirect(reverse('index')) pass
def check(request): name = request.POST['username'] chat = ChatRoom.objects.get(name="DRRR") try: ic = request.POST['icon'] except: ic = {} if not Users.objects.filter(username = name): #return HttpResponse(Users.objects.filter(username = name)) if not ic: # better to stay on the same page return HttpResponse("Please select an icon") else: new = Users(username = name, icon = ic) new.save() return render_to_response('room.html', {'user': new, 'chat': chat}) else: u = Users.objects.get(username = name) if u.icon == ic: return render_to_response('room.html', {'user': u, 'chat': chat}) else: u.icon = ic u.save() return render_to_response('room.html', {'user': u, 'chat': chat})
def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ u=Users(first_name='111',last_name='222',password='******',appellation='5555',email='*****@*****.**',id_no='130102198403261218',mobile_phone=13653319585) u.save() self.assertEqual((u.id>0),True)
def phonebook(request): html = '' for i in Users.get_phones([251, 298, 911, 256, 257, 250, 300, 240]): html += '%s - %s<br/>' % (i.extension, i.name) html = '<html><body>%s</body></html>' % html return render_to_response('pbx/index.html', {'phones': Users.get_phones([251, 298, 911, 256, 257, 250, 300, 240])})
def purge(): ''' Truncate all tables ''' Users.delete().execute() Inventory.delete().execute() AccessRights.delete().execute() Credentials.delete().execute()
def addUser(self, name, lastonLineTime, onlineStatus, ip): existUser = Users.objects.filter(name=name) if len(existUser) != 0: raise Exception("the Users is already exits") newUser = Users(name=name, ip=ip, onlineStatus=True, lastonLineTime=lastonLineTime) newUser.save()
def delete(self, id): jail = Users.first(id=id) msg = "The user could not be deleted." if jail: if Users.delete(jail): msg = "User deleted." cherrypy.session['flash'] = msg raise cherrypy.HTTPRedirect('/users')
def addUser(username, department, name, course, password, voted=False): '''Registers new user with the system including signature key generation and registration''' #generate private key key = RSA.generate(2048) encryptedPrivateKey = cryptography.symmetricEncrypt(key.exportKey(), password) p1 = Users(username=username, voted=voted, department=department, name=name, course=course, encryptedPrivateKey=encryptedPrivateKey) p1.save() return key.publickey().exportKey()
def _get_users_by_page(): """ :return:users, page """ total = Users.count_all() page = Page(total, _get_page_index(), 5) users = Users.find_by('order by created_at desc limit ?,?', page.offset, page.limit) return users, page
def get(self): count = Users.all().count() if count > 0: users = Users.all().fetch(count) for user in users: taskqueue.add(url='/birthdays', params={"email": user.email, "access_token": user.accessToken}) else: self.response.out.write("No users")
def get(self): count = Users.all().count() if count > 0: users = Users.all().fetch(count) for user in users: url = urlfetch.fetch("https://graph.facebook.com/me?access_token=" + user.accessToken, method=urlfetch.GET, deadline=20) profile = url.content self.response.out.write(profile+"<br>") else: self.response.out.write("No users")
def get(self): count = Users.all().count() if count > 0: users = Users.all().fetch(count) for user in users: # fb_user = facebook.get_user_from_cookie(self.request.cookies, APP_ID, APP_SECRET) # if fb_user: # access_token = fb_user['access_token'] # access_token = "AAAFgBAs8K8YBAGgNcgyoZCJVDcj5ZBPVM3ZBmR3XkTgDsCeUSzdlU4NUb6ZAo2o6WE0jZBz8399hBL2TzYlXW8Hv3BKZCWahwZD" taskqueue.add(url='/processUsers', params={"access_token": user.accessToken})
def check_new_user(wechat_u_id): # user = auth.authentication(username = '******', password = '******') this_user = Users.objects(wechat_user_id=wechat_u_id) if not this_user: this_user = Users(wechat_user_id = wechat_u_id, user_property = USER_PRO, active_level = 0, experience_points = 0) this_user.save() logger.info("Added new user") return True else: logger.info("Exiting User") return False
class Mike(webapp2.RequestHandler): def get(self): count = Users.all().count() if count > 0: users = Users.all() users.filter("facebookID = ", "691580472") users.fetch(1) for user in users: taskqueue.add(url='/mike', params={"email": user.email, "access_token": user.accessToken}) else:
def register_user(name, username, email, password, utype, admin=False): user = Users(name, username, email, password, utype=utype, admin=admin) token = utils.generate_string(length=64) user.email_token = token with app.app_context(): db.session.add(user) db.session.commit() join_activity = UserActivity(user.uid, 0) db.session.add(join_activity) db.session.commit() db.session.close() return True
def post(self): if self.request.get('name') != ''\ and self.request.get('password1') != ''\ and self.request.get('password2') != ''\ and (self.request.get('password1') == self.request.get('password2')): user = Users() user.name = self.request.get('name') # user.email = self.request.get('email') user.password = hashlib.md5(self.request.get('password1')).hexdigest() user.put() self.redirect('/') else: self.redirect("/register?error=1")
def addj(request): username = request.GET.get('username',None) password = request.GET.get('password',None) userList = Users.objects.all() groupList = Group.objects.all() for user in userList: if user.username == username and user != None: return render_to_response('home.html',locals()) else: request.session['username'] = username user = Users(username=username, password=password) user.save() return render_to_response('home.html',locals())
def register_user(username, password, passphrase=None, verbose=False): ''' Register a new user ''' if passphrase is None: passphrase = password crypt.rsa_gen(username, passphrase, verbose=verbose) hashed_password, salt = crypt.salt_hash(password) Users.create( username=username, salt=salt, password=hashed_password )
def user_signup(request): """ Create a new user Accepts: "email": <string> "first_name": <string> "last_name": <string> "password": <string> Returns: HTTP_200_OK: if the association is successful or "error": <string> Exception msg string Example POST payload: { "first_name": "foo", "last_name": "bar", "email": "*****@*****.**", "password": "******" } """ if request.method == 'POST': start_time = time.time() if set(['email', 'first_name', 'last_name', 'password']) != set(request.data.keys()): return Response({'error': "invalid params"}, status=status.HTTP_400_BAD_REQUEST) # if not re.match(r'[^@]+@[^@]+\.[^@]+', request.data['email']): # return Response({'error': "invalid email"}, status=status.HTTP_400_BAD_REQUEST) if Users.objects.filter(email__iexact=request.data['email']): return Response({'error': "user exists"}, status=status.HTTP_400_BAD_REQUEST) try: new_user = Users(email=request.data['email'], first_name=request.data['first_name'], last_name=request.data['last_name'], password=encrypt(request.data['password'])) new_user.save() logger.debug("user_signup: elapsed time: %s" % (time.time() - start_time)) return Response(status=status.HTTP_200_OK) except Exception as ex: str_ex = str(ex) logger.debug(("user_signup: %s", str_ex)) logger.debug("user_signup: elapsed time: %s" % (time.time() - start_time)) return Response({'error': str_ex}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) elif request.method == 'GET': err_dict = { 'error': 'invalid request', 'example POST payload': { "first_name": "foo", "last_name": "bar", "email": "*****@*****.**", "password": "******" } } return Response(err_dict, status=status.HTTP_400_BAD_REQUEST)
def create_user(update): msg = update.message q = Users.objects(id=msg.from_user.id) if not q: new_user = Users( id=msg.from_user.id, first_name=msg.from_user.first_name, last_name=msg.from_user.last_name, username=msg.from_user.username, chats=[msg.chat_id] ) new_user.save() else: q.update(add_to_set__chats=update.message.chat_id)
def get_results(): """ Used through AJAX to get datatables results """ results = Users.to_datatables(request.form) for item in results["data"]: temp = item["username"] item["username"] = """<a href="{0}">{1}</a>""".format(url_for('users.edit_user',userid=item["DT_RowId"]),temp) action_column = "" if item["active"] and str(current_user._id.value) != item["actiuni"]: action_column+="""<span> <a href="{0}" class="btn btn-xs btn-warning"><span class="glyphicon glyphicon-user" aria-hidden="true" data-toggle="tooltip" data-placement="top" title="Dezactiveaza utilizator"></span></a> </span> """.format(url_for('users.deactivate_user',userid=item["DT_RowId"])) elif not item["active"] and str(current_user._id.value) != item["actiuni"]: action_column+="""<span> <a href="{0}" class="btn btn-xs btn-success"><span class="glyphicon glyphicon-user" aria-hidden="true" data-toggle="tooltip" data-placement="top" title="Activeaza utilizator"></span></a> </span>""".format(url_for('users.activate_user',userid=item["DT_RowId"])) if str(current_user._id.value) != item["actiuni"]: action_column+="""<span> <a href="javascript:void(0)" onclick="DeletePage('{0}')" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-remove" aria-hidden="true" data-toggle="tooltip" data-placement="top" title="Sterge utilizator"></span></a> </span>""".format(url_for("users.delete_user",userid=item["DT_RowId"])) item["actiuni"] = action_column return jsonify(results)
def updateUserItem(request, itemID): if all(k in request.POST for k in ('secret_key', 'site_url', 'title', 'search_tags', 'note')): # get parameters secretKey = request.POST.get('secret_key') siteURL = request.POST.get('site_url') title = request.POST.get('title') searchTags = request.POST.get('search_tags') note = request.POST.get('note') fileIDs = request.POST.getlist('file_ids[]') tags = request.POST.getlist('tags[]') # get user user = Users.query(Users.secret_key == secretKey).get() if user: # update user item ItemService.updateUserItem(itemID, user, siteURL, title, searchTags, note, fileIDs, tags) return HttpResponse(json.dumps({'status': 'success'}), mimetype='application/json', status='200') else: return HttpResponse(json.dumps({'status': 'invalid_login'}), mimetype='application/json', status='403') else: return HttpResponse(json.dumps({'status': 'missing_param'}), mimetype='application/json', status='400')
def test_login_error_incorrect_password(self): u = Users.new_member('*****@*****.**', 'password123', 'Tom', 'Smith') form = LoginForm( email="*****@*****.**", password="******" ) self.client.post("/auth/login/", data=form.data) self.assertTemplateUsed("auth/login.html") self.assertMessageFlashed("Incorrect password for " + form.data["email"], "danger")
def verify_password(username_or_token, password): # Try to see if it's a token first user_id = Users.verify_auth_token(username_or_token) # if user_id is None try to verify username and password if user_id: user = session.query(Users).filter_by(id=user_id).one() else: user = session.query(Users).filter_by(username=username_or_token).first() # noqa: E501 if not user or not user.verify_password(password): return False g.user = user return True
def get_all_users(): #open connection with sqlite3.connect("./rare.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() #SQL query db_cursor.execute(""" SELECT u.id, u.first_name, u.last_name, u.email, u.username, u.password, u.is_staff, u.bio, u.created_on, u.active FROM Users as u """) #Initialize an empty list for users users = [] #convert rows into a python list dataset = db_cursor.fetchall() #Iterate through list of data returned for row in dataset: #create a user instance from current row user = Users(row['id'], row['first_name'], row['last_name'], row['email'], row['username'], row['password'], row['is_staff'], row['bio'], row['created_on'], row['active']) # postReaction = PostReaction(row['postReaction_id'], row['postReaction_user_id'], row['postReaction_post_id'], row['postReaction_reaction_id']) #add the new dictionaries to user instance #add user to users users.append(user.__dict__) #return the data return json.dumps(users)
def upload_file(): user_id = str(session['user_id']) store_file = "./static/profile_pics/" + str(user_id) print(f"store file path: {store_file}") if not os.path.exists(store_file): os.makedirs(store_file) print(f"ROUTE: upload_file") current_user = Users.query.get(user_id) if request.method == 'POST' and 'files' in request.files: for f in request.files.getlist('files'): profile_pic = secure_filename(f.filename) file_path = PROFILE_PIC_FOLDER + "/" + str(user_id) + "/" + profile_pic print(f"Uploading {profile_pic}") f.save(os.path.join(store_file, profile_pic)) flash('File(s) successfully uploaded') Users.update_user_profile_pic(current_user.id, file_path) db.session.commit() return redirect(url_for("show_profile_page", id=current_user.id))
def user_add(): context = base_context() if request.method == 'POST': id = request.form['id'] name = request.form['name'] password = request.form['password'] admin_user = request.form.get('admin_user') if admin_user == 'True': admin_user = True else: admin_user = False has_user = db.session.query(exists().where(Users.id == id)).scalar() if has_user is False: new_user = Users(id=id, name=name, admin_user=admin_user) new_user.set_hash(password) db.session.add(new_user) db.session.commit() return render_template('admin/add.html', **context) return render_template('admin/add.html', **context)
def fines(message): text = "Разбивка кто кому сколько должен:\n" total = 0 for user in Users.select().order_by(Users.fails.asc()).execute(): total += user.done for user in Users.select().execute(): if user.fails > 0: text += user.name + "(" + user.phone + " " + user.bank + ")" + " должен:\n" for other_user in Users.select().execute(): if other_user.tel_id != user.tel_id: Iowe = round((other_user.done / (total - user.done)) * getFine(user.fails)) TheyOwe = round( (other_user.done / (total - other_user.done)) * getFine(other_user.fails)) if Iowe > TheyOwe: text += str(Iowe - TheyOwe ) + "руб. - " + other_user.name + "\n" else: text += user.name + "(" + user.phone + " " + user.bank + ")" + " никому ничего не должен\n" bot.send_message(message.chat.id, text)
def user_panel(): temp_id = current_user.user_id user_to_update = search_users_id(temp_id) if request.method == "GET": return render_template("user_panel.html", user_to_update=user_to_update) else: password = request.form['password'] updated_user = Users(user_to_update[1], user_to_update[2], password, user_to_update[4]) update_users(temp_id, updated_user) return redirect(url_for("index"))
def test_insert_user(client): with app.app_context(): #insert(username, password, fullname, email, user_group, pillar, term, student_id, student_group, professor_id, coursetable) numUsers = len(Users.query.all()) print("\n[INFO] Inserting user, database should contain user & no. users should ++1") print("[INFO] No. of users before insert: {}".format(numUsers)) username = '******' fullname = 'Aiden Chia' email = '*****@*****.**' password = '******' user_group = 'student' Users.insert(username=username, password=password, fullname=fullname, email=email, user_group=user_group, pillar=None, term=None, student_id=None, student_group=None, professor_id=None, coursetable=None) new_numUsers = len(Users.query.all()) print("[INFO] No. of users after insert: {}".format(new_numUsers)) query = Users.query.filter_by(username='******').all() assert len(query) == 1 assert numUsers + 1 == new_numUsers
def handle_login(): json = request.get_json() db.session.add( Users(first_name=json['first_name'], last_name=json['last_name'], username=json['username'], date_of_birth=json['date_of_birth'], email=json['email'])) db.session.commit() return jsonify(json)
def get(self): """ Muestra todos los usuarios con un resumen de la cantidad de ventas y monto total. ej: /users/information """ users = Users.get_all() users.raw_output() users = users.all() user_json = [serial(user) for user in users] add_information(users) return user_json, 201
def create_or_login(resp): session['openid'] = resp.identity_url user = Users.query.filter_by(OpenId=resp.identity_url).first() if user is None: user = Users(OpenId=session['openid'], Options=json.dumps(app.config['USER_DEFAULT_OPTIONS'])) db.session.add(user) db.session.commit() flash(u'Successfully signed in') g.user = user return redirect(oid.get_next_url())
def subapply(): if 'loginbean' in session: loginbean = session['loginbean'] if request.method == 'POST': shopid = request.form.get('shopid') #接参,接收id前端传来请求 if shopid == None: # 如果数据库里没有执行下面 shop = Shops() #--------修改users表中role=2(审核中 )---------- # u = Users.objects(_id=shop.uid).updata(inc__role=1) #增加 # u = Users.objects(_id=shop.uid).update(set__role=2) #修改 # msg.save() else: shop = Shops.objects(_id=shopid, uid=loginbean['id']).first() # print(shop['uid']) shop['uid'] = loginbean['id'] shop['shopname'] = request.form.get('shopname') shop['address'] = request.form.get('address') shop['lng'] = float(request.form.get('lng')) shop['lat'] = float(request.form.get('lat')) shop['tel'] = request.form.get('tel') #以上是入库操作 # shopname = request.form.get('shopname') app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd( ) + '/static/photos' # 文件储存地址 configure_uploads(app, photos) #使用configure_uploads()方法注册并完成相应的配置 fArr = ('idcard', 'ownercard', 'blicense', 'hlicense') for item in fArr: if item in request.files: f = request.files[item] if f and allowed_file(f.filename): # 判断是否是允许上传的文件类型 filename = photos.save(request.files[item]) # print(filename) shop[item] = '/static/photos/' + filename # --------构建shops商家,入库插入数据 updtime = time.strftime('%Y-%m-%d %H:%M:%S') #将时间转换成整体显示 # updtime = time.time() shop.updtime = updtime shop.flag = 0 if shopid == None: # 如果数据库里没有执行下面 shop.createtime = updtime shop.save() u = Users.objects(_id=shop.uid).update(set__role=2) loginbean['role'] = 2 session['loginbean'] = loginbean return redirect('/home') else: return '<script>alert("session过期,请重新登录");location.href="/";</script>'
def gettoken(request): auth_code = request.GET["code"] redirect_uri = request.build_absolute_uri(reverse("oauth:gettoken")) token = get_token_from_code(auth_code, redirect_uri) access_token = token["access_token"] user = get_me(access_token) refresh_token = token["refresh_token"] #expires_in is in seconds expires_in = token["expires_in"] expiration = int(time.time()) + expires_in - 120 #saving the session request.session['access_token'] = access_token request.session['refresh_token'] = refresh_token request.session['token_expires'] = expiration #npuser = new_possible_user npuser = Users() global current_user current_user = user['mail'] npuser.email = user['mail'] npuser.username = user['displayName'] try: npuser.save() except: pass return HttpResponseRedirect(reverse('oauth:token'))
def register(): if not request.is_json: return jsonify({"msg": "Invalid format"}), 400 email = request.json.get('email', None) password = request.json.get('password', None) if not email or email == '': return jsonify({"msg": "ERROR: Enter correct mail"}), 400 if not password or password == '': return jsonify({"msg": "ERROR: Enter correct password"}), 400 users = Users.query.filter_by(email=email).first() if users: return jsonify({"msg": "ERROR: Username all ready exist"}), 400 users = Users() users.email = email users.password = bcrypt.generate_password_hash(password) users.role_id = 2 db.session.add(users) db.session.commit() access_token = create_access_token(identity=users.email) data = {"access_token": access_token, "users": users.serialize()} return jsonify(data), 201
def auth_callback(): state = request.args.get("state") if "error" in request.args: flash("Error: {}".format(request.args.get("error"))) if current_user.is_anonymous: args = { "code": request.args.get("code"), "client_id": app.config["STRAVA_CLIENT_ID"], "client_secret": app.config["STRAVA_CLIENT_SECRET"] } client = stravalib.Client() try: access_token = client.exchange_code_for_token(**args) except Exception as e: log.error("authorization error:\n{}".format(e)) flash(str(e)) return redirect(state) user_data = Users.strava_data_from_token(access_token) # log.debug("user data: {}".format(user_data)) try: user = Users.add_or_update(**user_data) except Exception as e: log.exception(e) user = None if user: # remember=True, for persistent login. login_user(user, remember=True) # log.debug("authenticated {}".format(user)) EventLogger.new_event(msg="authenticated {}".format(user.id)) else: log.error("user authenication error") flash("There was a problem authorizing user") return redirect( request.args.get("state") or url_for("main", username=user.id))
def register(): if not request.is_json: return jsonify({"msg": "Formato invalido!"}), 400 email = request.json.get('email', None) password = request.json.get('password', None) if not email or email == '': return jsonify({"msg": "Ingresa un correo valido!"}), 400 if not password or password == '': return jsonify({"msg": "Ingresa un password!"}), 400 users = Users.query.filter_by(email=email).first() if users: return jsonify({"msg": "Usuario ya existe!"}), 400 users = Users() users.email = email users.password = bcrypt.generate_password_hash(password) users.role_id = 2 db.session.add(users) db.session.commit() access_token = create_access_token(identity=users.email) data = {"access_token": access_token, "users": users.serialize()} return jsonify(data), 201
def render_registration_page(): form = RegistrationForm() if form.validate_on_submit(): print("sumitted", flush=True) username = form.username.data password = form.password.data user_type = form.usertype.data contact = form.contact.data credit_card = form.credit_card.data is_part_time = form.is_part_time.data postal_code = form.postal_code.data hashed_password = bcrypt.generate_password_hash(password).decode( 'utf-8') # query = "INSERT INTO users(username, contact, card, password, usertype, isPartTime, postalcode) VALUES ('{}', '{}', '{}', '{}', '{}', '{}', '{}')" \ # .format(username, contact, credit_card, hashed_password, user_type, is_part_time, postal_code) # db.session.execute(query) # db.session.commit() user1 = Users(username=username, usertype=user_type, contact=contact, card=credit_card, postalcode=postal_code, password=hashed_password) role = Role.query.filter_by(name=user_type).first() user1.roles.append(role) db.session.add(user1) #query = "SELECT * FROM role WHERE name = '{}'".format(user_type) #givenRole = db.session.execute(query).fetchone() #query = "INSERT INTO user_roles(contact, usertype) VALUES ('{}', '{}')".format(contact, user_type) #db.session.execute(query) db.session.commit() canparttime1 = CanPartTime(contact=contact, isparttime=is_part_time) db.session.add(canparttime1) db.session.commit() #query = "INSERT INTO users(username, contact, card, password, usertype, isPartTime, postalcode) VALUES ('{}', '{}', '{}', '{}', '{}', '{}', '{}')" \ # .format(username, contact, credit_card, hashed_password, user_type, is_part_time, postal_code) # print(query, flush=True) # db.session.execute(query) # print("done", flush=True) # db.session.commit() print("commited", flush=True) flash('Your account has been created! You are now able to log in', 'success') return redirect("/login") print("rendered", flush=True) return render_template("registration.html", title='Registration', form=form)
def setUpClass(cls): #empty database db.session.commit() db.session.close() db.drop_all() db.create_all() #set up database admin_role = Role(name='admin') db.session.add(admin_role) user_role = Role(name='user') db.session.add(user_role) teacher_role = Role(name='teacher') db.session.add(teacher_role) user = Users(username='******', first_name='first', last_name='last', role_id=user_role.id) user.set_password('password') db.session.add(user) db.session.commit() db.session.close()
def user_register(request): from validator import on_user_registration from utility import format_on_user_registration from models import Users on_user_registration(request) data = format_on_user_registration(request) user = Users(**data).save() if user: return True else: from upload_service.middleware.exception.ApiBaseException import ApiBaseException raise ApiBaseException(message='Failed To Register User')
def get_leaderboard(): mes = "Лидер борд 👊🏼\n\n" for i, user in enumerate(Users.select().order_by( Users.done.desc()).execute()): if user.fails: mes += f"{i + 1}. {user.name} - {user.done} [{user.rests}] (-{getFine(user.fails)})" else: mes += f"{i + 1}. {user.name} - {user.done} [{user.rests}] 💪" if user.sick: mes += " - на больничном \n" else: mes += "\n" return mes
def signup(): #get 요청 단순히 페이지 표시 post요청 회원가입-등록을 눌렀을때 정보 가져오는것 form = RegisterForm() if form.validate_on_submit(): # POST검사의 유효성검사가 정상적으로 되었는지 확인할 수 있다. 입력 안한것들이 있는지 확인됨. #비밀번호 = 비밀번호 확인 -> EqulaTo users = Users() #models.py에 있는 users users.userid = form.data.get('userid') users.password = form.data.get('password') users.username = form.data.get('username') users.birthday_year = form.data.get('birthday_year') users.birthday_month = form.data.get('birthday_month') users.birthday_day = form.data.get('birthday_day') users.sex = form.data.get('sex') users.phone = form.data.get('phone') print(users.userid, users.password) #회원가입 요청시 콘솔창에 ID만 출력 (확인용, 딱히 필요없음) db.session.add(users) # id, name 변수에 넣은 회원정보 DB에 저장 db.session.commit() #커밋 return redirect('/') #post요청일시는 '/'주소로 이동. (회원가입 완료시 화면이동) return render_template('signup.html', form=form)
def __init__(self, log, course, answers, courses): self.course_name = '' self.users = Users() self.tasks = Tasks() self.modules = Modules() self.content = Content() self._parse(log) for item in (self.users, self.tasks, self.modules, self.content): item.update_data(course, answers) self.course_long_name = courses[self.course_name]
def processLogin(): if len(request.form['password']) < 1 and len(request.form['username']) < 1: flash("Enter a Username and Password") return redirect("/login") else: login_check = Users.validate_login(request.form) if login_check == False: return redirect("/login") else: session['user_id'] = login_check.id session['first_name'] = login_check.first_name session['last_name'] = login_check.last_name return redirect("/home")
def main(argv=sys.argv): print 'called' if len(argv) != 2: usage(argv) config_uri = argv[1] setup_logging(config_uri) settings = get_appsettings(config_uri) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: model = Users(first_name='Julien', last_name='waddle') DBSession.add(model)
def register(): form = RegistrationForm() if form.validate_on_submit(): hash_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user = Users(username=form.username.data, email=form.email.data, password=hash_password) db.session.add(user) db.session.commit() flash(f'Account created for {form.username.data}!', 'success') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def sign_up(self, user, password): """ this method takes a user and a password and checks if it exists in the database, if not then it will create a new Users object containing the user and password and will insert it into the database :param user: :param password: :return: """ if not self.Session().query(Users).filter(Users.user == user).first(): user = Users(user, password) self._insert_item(user) return True return False
def registration(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] email = request.POST['email'] try: if User.objects.get(email=email): return HttpResponseRedirect("/registration/") except: pass try: if User.objects.get(username=username): return HttpResponseRedirect("/registration/") except: pass u = User(username=username, password=password, email=email) u.save() U = Users(user=u, karma=0, transcriptions=0, annotations=0) U.save() return HttpResponseRedirect("/") else: return render_to_response("registration.html", locals())
def get_leaderboard(): mes = "Лидер борд 👊🏼\n\n" day = datetime.date.today().weekday() for i, u in enumerate(Users.select().order_by( Users.done.desc()).execute()): rest = 2 - (day - u.done_per_week) if u.fails: mes += f"{i + 1}. {u.name} - {u.done} [{rest}] (-{taxes[u.fails]})\n" else: mes += f"{i + 1}. {u.name} - {u.done} [{rest}] 💪\n" print(u.name, u.tel_id) return mes
def signup(): """ get the sign up form and add new user to DB. """ form = SignupForm() if form.validate_on_submit(): user = Users.signup(form.name.data, form.email.data, form.password.data) do_login(user) add_user_to_g() print(g.user.fullname) return redirect('/') return render_template("register.html", form=form)
def get(self, slug): user = Users.select().where(Users.id == slug) if user: # Retrieve users post, comment, and like history user = Users.select().where(Users.id == slug).get() posts = Posts.select().where(Posts.user_id == slug) if posts: posts = (Posts.select().where(Posts.user_id == slug).order_by( Posts.created.desc())) comments = Comments.select().where(Comments.user_id == slug) if comments: comments = (Comments.select().where( Comments.user_id == slug).order_by( Comments.created.desc())) likes = Likes.select().where(Likes.user_id == slug) if likes: likes = (Likes.select().where(Likes.user_id == slug).order_by( Likes.created.desc())) loggedInUser = self.current_user numPosts = Posts.select().where(Posts.user_id == slug).count() numComments = Comments.select().where( Comments.user_id == slug).count() numLikes = Likes.select().where(Likes.user_id == slug).count() totalLikes = Likes.select( Likes.post_id).join(Posts).join(Users).where( Posts.user_id == slug).count() return self.render_template( "author.html", { 'posts': posts, 'numPosts': numPosts, 'numComments': numComments, 'numLikes': numLikes, 'comments': comments, 'likes': likes, 'user': user, 'totalLikes': totalLikes, 'loggedInUser': loggedInUser }) return self.redirect("/")