def system_backup_restore(): action = '回滚' userid = session['userid'] user_info = User.get_user_by_userid(userid).get('user_info') role = user_info.get('role') or 1 auth = user_info.get('auth') or [] if role < 100: return jsonify({'code': 20000, 'msg': '没有权限'}) elif role == 100: if action not in auth: return jsonify({'code': 20000, 'msg': '没有权限'}) data = request.get_json() dump_name = data.get('dump_name') if not dump_name: return jsonify({'code': 44000}) res = mongo_backup.restore(dump_name) if not res: return jsonify({'code': 44000}) if role == 100: auth.remove(action) user_info['auth'] = auth User.set_user_info([userid], [user_info]) return jsonify({'code': 20000})
def register(): payload = request.form or request.json id = payload.get('id') password = payload.get('password') name = payload.get('name') phone = payload.get('phone') email = payload.get('email') user = User( id=id, name=name, password=password, phone=phone, email=email, ) user.save() join_method = payload.get('join_method', 'local') if join_method != 'local': social_api_token = payload['social_api_token'] _add_user_social_login( user.id, join_method, social_api_token, ) return (jsonify( access_token=create_access_token(identity=id), refresh_token=create_refresh_token(identity=id), ), 201)
def setUp(self): self.u0 = User('U0G9QF9C6') self.u0.email = '*****@*****.**' self.u0.github_id = '305834954' self.u1 = User('Utheomadude') self.u1.email = '*****@*****.**' self.u1.github_id = '349850564' self.admin = create_test_admin('Uadmin') self.lead = User('Ualley') self.lead.email = '*****@*****.**' self.lead.github_id = '2384858' self.lead.permissions_level = Permissions.team_lead self.t0 = Team('305849', 'butter-batter', 'Butter Batters') self.t0.add_member(self.u0.github_id) self.t0.add_member(self.lead.github_id) self.t0.add_team_lead(self.lead.github_id) self.t1 = Team('320484', 'aqua-scepter', 'Aqua Scepter') self.t1.add_member(self.u1.github_id) self.t2 = Team('22234', 'tiger-dear', 'Shakespearean') self.db = MemoryDB(users=[self.u0, self.u1, self.admin, self.lead], teams=[self.t0, self.t1, self.t2]) self.cmd = ExportCommand(self.db)
def project_manage(): projectName = request.args.get('projectName', None) owner = request.args.get('owner', None) page = int(request.args.get('page', 1)) - 1 select = {} if projectName: select['projectName'] = projectName if owner: user = User.objects(username=owner).first() if not user: return jsonify(build_response(data=[])) select['owner'] = str(user.id) project_list = [] projects: List[Project] = Project.objects(**select) total_page = math.ceil(len(projects) / number_per_page) for project in projects[page * number_per_page:page * number_per_page + number_per_page]: owner_name = User.get_user_by_id( project.owner).username if not owner else owner project_list.append({ 'projectId': str(project.id), 'projectName': project.projectName, 'owner': owner_name, 'memberNum': len(project.member) + 1, 'videoNum': len(project.hasVideo), 'meetingNum': len(project.hasMeeting), 'alive': project.alive }) data = {'totalPage': total_page, 'projectList': project_list} return jsonify(build_response(data=data))
def get(self, action = '', argument=''): """ Validate if username is available""" res = dict(status=STATUS_OK) if action == 'validateusername': logging.info("Query for username" + argument) user = User.all() user.filter("username ="******"%40","@") logging.info("Query for email" + email) user = User.all() user.filter("email =", email) res['available'] = 'No' if user.count() == 0: res['available'] = 'Yes' self.response.headers['content-type'] = 'text/plain' self.response.out.truncate(0) self.response.out.write(self._encode_response(res)) self.response.out.write('\n')
def create(self): p = { 'type': self.get_argument_enum('type', [User.TYPE_NORMAL, User.TYPE_ADMIN], User.TYPE_NORMAL), 'name': self.get_argument('name', ''), 'password': self.get_argument('password', ''), 'username': self.get_argument('username', ''), } if not p['password']: self.finish({'code': 1, 'msg': u'密码不能为空'}) return if not p['username']: self.finish({'code': 2, 'msg': u'用户名不能为空'}) return q = self.session.query(Passport).filter_by(username=p['username']) if self.session.query(q.exists()).scalar(): self.finish({'code': 3, 'msg': u'用户名已存在'}) return user = User(type=p['type'], name=p['name'], create=time.time()) self.session.add(user) self.session.flush() key = base64.urlsafe_b64encode(uuid.uuid4().hex)[:16] ps = key + hmac.new(key, p['password'], hashlib.sha256).hexdigest() passport = Passport(user=user.id, username=p['username'], password=ps, create=time.time()) self.session.add(passport) self.session.commit() self.finish({'code': 0, 'data': user.dict()})
def register(): from app import db form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data, phone_num=form.phone_num.data) u = User(form.username.data, form.password.data,form.email.data, form.phone_num.data) if (u.isExisted()): message='用户名已存在' return render_template('register.html',message=message, form=form) else: # from twilio.rest import Client # # Your Account Sid and Auth Token from twilio.com/console # account_sid = 'AC379c4955bd0f3e0f9f52ec086dcb7c1c' # auth_token = '79ff623bc3b52af312c0562cad571c66' # # auth_token = '8240d2517918932a997b8bb195911234' # client = Client(account_sid, auth_token) # message = client.messages.create( # from_='+12482152894', # body=str(form.username.data)+'用户名已由%s注册'%form.phone_num.data, # to='+8615966652606' # # to='+8618866812508' # ) # print(message.sid) db.session.add(user) db.session.commit() return redirect(url_for('auth.login'))#重定向登陆页面 return render_template('register.html', form=form)
def makeUsers(amount: int = 20) -> List[User]: r = [] for _ in range(amount): u = User(str(uuid4())) u.github_username = u.slack_id r.append(u) return r
def test_find_user_multiple(self): NICK, NAME = 'multiple_228', 'Marin Komitsky' sneaky_user = User(nick=NICK, name=NAME, avatar='') sneaky_user2 = User(nick=NICK + '_1', name=NAME + '_1', avatar='') db.session.add_all([sneaky_user, sneaky_user2]) db.session.commit() def _check_multiple(user): self.assertTrue(int(user['id']) in [sneaky_user.id, sneaky_user2.id]) self.assertTrue(user['nick'] in [sneaky_user.nick, sneaky_user2.nick]) self.assertTrue(user['name'] in [sneaky_user.name, sneaky_user2.name]) with self.subTest('Length on many matches'): users = json.loads(find_user(nick=NICK)) self.assertEqual(len(users), 2) with self.subTest('Every user is correct'): users = json.loads(find_user(nick=NICK)) for user in users: _check_multiple(user) with self.subTest('Many by first 3 letters nick'): users = json.loads(find_user(nick=NICK[:3])) self.assertEqual(len(users), 2) for user in users: _check_multiple(user) with self.subTest('Many by first 3 letters name'): users = json.loads(find_user(name=NAME[:3])) self.assertEqual(len(users), 2) for user in users: _check_multiple(user)
def setUp(self): #app = main.app.test_client() db.create_all() db.session.add(User("mtest","*****@*****.**", "0d66db5457fc3e401b0eea9e1ba0a1dc","121","picurl.jpeg")) db.session.add(User("m2test","*****@*****.**", "0d66db5457fc3e401b0eea9e1ba0a1dc","345","mypic.jpeg")) env1 = Envelope("env1","mtest","someone","369") env1.eowner = "1" db.session.add(env1) env2 = Envelope("env2","mtest","no one","248") env2.eowner = "1" db.session.add(env2) #env1 = Envelope.query.filter_by(handle="369").first() db.session.add(Image("1","image1.com","image1.jpg")) db.session.add(Image("1","image2.com","image2.png")) db.session.add(Image("1","image3.com","image3.gif")) db.session.add(Image("2","image-a.com","img.jpg")) db.session.add(Image("2","image-b.com","img.png")) db.session.add(History("1","V","1",None)) db.session.add(History("1","V","2",None)) db.session.add(History("1","D","2","3")) db.session.add(History("1","D",None,"1")) db.session.add(History("1","C","1",None)) db.session.add(History("2","C","1",None)) db.session.commit()
def test_user_equality(): """Test the User class method __eq__() and __ne__().""" user = User("brussel-sprouts") user2 = User("brussel-sprouts") user3 = User("brussel-trouts") assert user == user2 assert user != user3
def register() -> Response: """Register a new user. Returns: response: flask.Response object with the application/json mimetype. """ if not request.is_json: abort(400) user_repository = UserRepository() # creating a User object user = User() user.username = request.json.get('username') user.password = request.json.get('password') # validating the user is_invalid = user_repository.is_invalid(user) if not is_invalid: user_repository.save(user) return make_response( jsonify({ 'status': 'success', 'data': user.serialize() }), 200) else: response = make_response( jsonify({ 'status': 'fail', 'data': is_invalid }), 400) return response
def test_the_update_method_of_user_repository(app): """ GIVEN the UserRepository class WHEN the method update(user) is called THEN check session method calls and user data """ from app.model import UserRepository, User user_repository = UserRepository() user_repository.session = UnifiedAlchemyMagicMock() user = User(username=get_unique_username(), password="******") user_repository.session.add(user) user_repository.session.commit() # updating username_edited = get_unique_username() user.password = "******" user.username = username_edited user_repository.update(user) # user_repository.session.commit.assert_called_once_with() assert check_password_hash(user.password, "1234") assert user.username == username_edited assert user.serialize() == { 'id': str(user.id), 'username': username_edited } assert str(user) == '<User %r>' % (username_edited)
def post(self): args = self.parse.parse_args(strict=True) phone = args['phone'] code = args['code'] zone = args['zone'] res = MobSMS(sms_key).verify_sms_code(zone, phone, code, debug=True) if res == 200: user = query(User).filter_by(tel=phone).first() if not user: user = User(None, phone, None, None, None, None) user.logintoken = Auth.generateTempToken(user) add(user) try: commit() msg = Message(user.user2dict(), None, 201) except Exception as e: rollback() print(e) msg = Message(None, "cannot commit to db", -1) return msg.response return Message(user.user2dict(), None, 200).response elif res == 467: return Message(None, "请求校验验证码频繁", 467).response elif res == 468: return Message(None, "验证码错误", 468).response
def test_edit_user_name(self) -> None: """Test edit user command API to edit user's name.""" self.mock_facade.retrieve.return_value = self.test_user self.testapi.user_edit(self.test_user_id, name="rocketeer") edited_user = User(self.test_user_id) edited_user.name = "rocketeer" self.mock_facade.store.assert_called_once_with(edited_user)
def test_password_hash(): user = User(id=1, username='******') word = "haircut" user.password = word assert user.verify_password(word)
def users(): result = [] # respond to GET request if request.method == 'GET': for user in User.query.all(): result.append(user.to_json()) elif request.method == 'POST': if hasattr(request, 'get_json'): save_data = request.get_json(True, True) else: save_data = request.json save_data.pop('password-check', None) try: user = User(**save_data) if user.validate(): db.session.add(user) db.session.commit() result = { 'success': True, 'id': user.id } else: return abort(500, 'Validation error: ' + '; '.join(user.validation_errors)) except Exception, e: log.error("Error creating user: %r; DATA=%r", e, save_data) return abort(500, 'Saving error')
def register_doctor(): """Register Form""" if request.method == 'GET': return render_template('register_doctor.html', days=User.days) elif request.method == 'POST': try: day_avail_list = request.form.getlist('docavail') avails = User.get_not_avail_days(day_avail_list) print(avails) avails1 = ",".join(day_avail_list) new_user = User(username=request.form['username'], usertype=User.Doctor, email=request.form['email'], password=request.form['password'], dayavail=avails, day_avail_s=avails1, starttime=request.form['timestart'], endtime=request.form['timeend'], hospital=request.form['hospitalname']) db.session.add(new_user) db.session.commit() return render_template('login.html') except Exception as e: print(str(e)) error = "Error.Username unavailable.Please try again \ with a different username" return render_template('register_doctor.html', error=error, days=User.days) return render_template('register_doctor.html', days=User.days)
def add_user(self): """Adds Test user to database""" try: user = User.query.filter_by(Client_id='testuser').first() db.session.delete(user) db.session.commit() user2 = User.query.filter_by(Client_id='testuser2').first() db.session.delete(user2) db.session.commit() except: pass pass_hash = bcrypt_sha256.encrypt("password", rounds=12) test_user_insert = User(Client_id='testuser', Password=pass_hash, api_key='api-key', current_login_ip='127.0.0.1') db.session.add(test_user_insert) db.session.commit() test_user_insert_2 = User(Client_id='testuser2', Password=pass_hash, api_key='api-key', current_login_ip='127.0.0.2') db.session.add(test_user_insert_2) db.session.commit() return test_user_insert
def create_users(db): print('[*] {0} - Adding users to datbase'.format(datetime.now())) # Create users from app.model import User # Sally user existing_user = User.query.filter_by(email='*****@*****.**').first() if existing_user is None: user = User(name='Sally', email='*****@*****.**', password=generate_password_hash('password123', method='sha256'), website='google.com', balance=100) db.session.add(user) # Bob user existing_user = User.query.filter_by(email='*****@*****.**').first() if existing_user is None: user = User(name='Bob', email='*****@*****.**', password=generate_password_hash('Password123!', method='sha256'), website='google.com', balance=0) db.session.add(user) # Commit users to database db.session.commit() # Query all users users = User.query.all() print(users)
def post(self): args = self.parse.parse_args(strict=True) phone = args['phone'] code = args['code'] zone = args['zone'] res = MobSMS(sms_key).verify_sms_code(zone, phone, code, debug=True) if res == 200: user = query(User).filter_by(tel=phone).first() if not user: user = User(None, phone, None, None, None, None); user.logintoken = Auth.generateTempToken(user) add(user) try: commit() msg = Message(user.user_full2dict(), None, 201) except Exception as e: rollback() print(e) msg = Message(None, "cannot commit to db", -1) return msg.response return Message(user.user_full2dict(), None, 200).response elif res == 467: return Message(None, "请求校验验证码频繁", 467).response elif res == 468: return Message(None, "验证码错误", 468).response
def test_get_returns_200_with_all_users_list(self): # Given user_1 = User(username='******', email='*****@*****.**', password_hash='hash') user_2 = User(username='******', email='*****@*****.**', password_hash='hash') self.db.session.add(user_1) self.db.session.add(user_2) self.db.session.commit() expected = [{ 'id': 1, 'username': '******', 'email': '*****@*****.**', 'email_confirmed': False }, { 'id': 2, 'username': '******', 'email': '*****@*****.**', 'email_confirmed': False }] # When response = self.client.get('/api/users') # Then self.assert200(response) self.assertEqual(expected, response.json)
def test_edit_user_major(self) -> None: """Test edit user command API to edit user's major.""" self.mock_facade.retrieve.return_value = self.test_user self.testapi.user_edit(self.test_user_id, major="cpen") edited_user = User(self.test_user_id) edited_user.major = "cpen" self.mock_facade.store.assert_called_once_with(edited_user)
def register(): values = request.get_json() required = ['username', 'last_name', 'first_name', 'password', 'email', 'profile_pic', 'gender', 'age'] if not all(k in values for k in required): return 'Missing values', 400 email = values.get('email') username = values.get('username') last_name = values.get('last_name') first_name = values.get('first_name') password = values.get('password') gender = values.get('gender') age = values.get('age') profile_pic = values.get("profile_pic") if re.match(r"[^@]+@[^@]+\.[^@]+", email) and len(password) > 4: user = User.get_by_email(email) user_name = User.get_by_username(username) if user_name: return response('failed', 'Failed, username already exists', 202) if not user: token = User(email=email, password=password, first_name=first_name, last_name=last_name, username=username, gender=gender, age=age, profile_pic=profile_pic).save() return response_auth('success', 'Successfully registered', token, 201) else: return response('failed', 'Failed, User already exists, Please sign In', 202) return response('failed', 'Missing or wrong email format or password is less than four characters', 202)
def get_all_challenges(current_user): # challenges = Challenge.get_challenge_by_user_id(current_user.id) challenges = Challenge.get_challenge_within_date_by_user_id(current_user.id, datetime.datetime.now()) resp = [] for challenge in challenges: user = Challenge.get_creator(challenge.id) username = User.getusername(user.user_id) my_format = "%Y-%m-%d %H:%M:%S" start_date = datetime.datetime.strptime(str(challenge.start_date), my_format).date() new_date = datetime.datetime.strptime(str(challenge.end_date), my_format).date() users = Challenge.get_users_performance(challenge.post_id) challenge_users = [] for user in users: user_name = User.getusername(user.user_id) challenge_users.append({ 'username': user_name, 'steps': Challenge.get_user_steps_by_challenge(datetime.datetime.now().date(), start_date, user.user_id), 'role': user.role }) resp.append({ 'steps': Challenge.get_user_steps_by_challenge(datetime.datetime.now().date(), start_date, current_user.id), 'start_date': challenge.start_date, 'goal': challenge.goal, 'role': challenge.role, 'challenge_name': challenge.challenge_name, 'challenge_description': challenge.challenge_description, 'end_date': str(new_date), 'creator': username, 'image_url': Post.get_post_image_url(challenge.post_id), 'challenge_id': challenge.id, 'users': challenge_users }) return jsonify(resp), 200
def test_expired_confirmation_token(self): u = User(password='******') db.session.add(u) db.session.commit() token = u.generate_confirmation_token(1) time.sleep(2) self.assertFalse(u.confirm(token))
class UserModelTest(unittest.TestCase): def setUp(self): self.new_user=User(username = '******',email = '*****@*****.**', password='******') self.user_Trial = User(username = '******',pass_secure = 'potato', email = '*****@*****.**') def test_password_setter(self): self.assertTrue(self.new_user.pass_secure is not None) def test_no_access_password(self): with self.assertRaises(AttributeError): self.new_user.password def test_password_verification(self): self.assertTrue(self.new_user.verify_password('banana')) def test_save_user(self): self.new_user.save_user() self.assertTrue(len(User.query.all())>0) def test_check_instance_variables(self): self.assertEquals(self.user_Trial.username,'Kel') self.assertEquals(self.user_Trial.password,'banana') self.assertEquals(self.user_Trial.email,"*****@*****.**") def tearDown(self): User.query.delete()
def register() -> Response: if not request.is_json: abort(400) is_invalid = u.is_invalid(request.json) if not is_invalid: user = User(email=request.json.get('email'), password=request.json.get('password')) db.session.add(user) db.session.commit() response = make_response( jsonify({ 'status': 'success', 'data': user.serialize() }), 200) else: response = make_response( jsonify({ 'status': 'fail', 'data': is_invalid }), 400) return response
def on_post(self, req, res): session = req.context['session'] user_req = self.load_request(req, res) if user_req is not None: auth_id = AUTH_ID_EMAIL % user_req['email'] user = User() user.username = user_req['username'] user.email = user_req['email'] user.password = hash_password(user_req['password']).decode('utf-8') user.lat = user_req['lat'] user.lng = user_req['lng'] user.phone = user_req['phone'] user.auth_id = auth_id user.token = encrypt_token(auth_id + ':' + uuid()).decode('utf-8') user.attr = user_req['attr'] session.add(user) res.status = falcon.HTTP_201 res.body = self.to_json({ 'meta': { 'code': 201 } }) else: self.abort(falcon.HTTP_400, "Invalid Parameter")
def profile(): if request.method == 'GET': return SuccResponse({'name': User.get_by_id(current_user.id).name}) req_data = request.json name = req_data.get('name', None) old_password = req_data.get('old_password', None) password = req_data.get('password', None) confirm_password = req_data.get('confirm_password', None) if not name: return ErrResponse() user = User.get_by_id(current_user.id) print(name, old_password, password, confirm_password) if not any([old_password, password, confirm_password]): user.name = name user.update() elif all([old_password, password, confirm_password]): if not user.check_password(old_password): return ErrResponse() if password != confirm_password: return ErrResponse() user.name = name user.set_password(password) user.update() return SuccResponse() else: return ErrResponse() return SuccResponse()
def test_edit_user_position(self) -> None: """Test edit user command API to edit user's position.""" self.mock_facade.retrieve.return_value = self.test_user self.testapi.user_edit(self.test_user_id, pos="dev") edited_user = User(self.test_user_id) edited_user.position = "dev" self.mock_facade.store.assert_called_once_with(edited_user)
def on_get(self, req, res): session = req.context["session"] user_req = req.context["data"] try: if user_req.get("user_id"): user_db = [ User.find_by_user_id(session=session, user_id=user_req["user_id"]) ] elif user_req.get("shared_id"): user_db = [ User.find_by_shared_id(session=session, id=user_req["shared_id"]) ] else: user_db = session.query(User).all() if user_db: userinfo_db = [] # fetching both user and userinfo table for user in user_db: user_details = user.to_dict() user_details.update( user.userinfo[0].to_dict() if user.userinfo else {}) userinfo_db.append(user_details) self.on_success(res, userinfo_db) except NoResultFound: raise UserNotExistsError( "user id: %s, shared id: %s" % (user_req.get("user_id"), user_req.get("shared_id")))
def test_edit_user_biography(self) -> None: """Test edit user command API to edit user's biography.""" self.mock_facade.retrieve.return_value = self.test_user self.testapi.user_edit(self.test_user_id, bio="I'm testing") edited_user = User(self.test_user_id) edited_user.biography = "I'm testing" self.mock_facade.store.assert_called_once_with(edited_user)
def facade_retrieve_side_effect(*args, **kwargs): """Return a side effect for the mock facade.""" if args[0] == Project: return Project("", []) else: calling_user = User(user) calling_user.permissions_level = Permissions.admin return calling_user
def test_ping(self): u = User(password='******') db.session.add(u) db.session.commit() time.sleep(2) last_seen_before = u.last_seen u.ping() self.assertTrue(u.last_seen > last_seen_before)
def regist(): if request.form: form = request.form user = User(email=form['email'],username=form['username']) err = user.save() if err: return err return render_template('index.html') return render_template('regist.html')
def add_user(): user_form = UserForm() if user_form.validate_on_submit(): user = User(name=user_form.data['name']) # TODO : currently if we try to save an user with a name already in database # TODO : the use is not saved but it returns no error, maybe we have to find a way to return # TODO : error saying "Name already in database" user.save() return redirect('/users') return render_template('user.new.jinja2', form=user_form)
def POST(self): data = web.input() user = User( email=data.email, password=data.password ) login_response = user.login() if login_response == 0: return web.seeother('/@'+self.session.user.username) else: return self.render('signin.html',error=login_response)
def signup(): form = Signup() if form.validate_on_submit(): user = User(name=form.name.data, email=form.email.data, password=form.password.data) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() send_email(user.email, "Confirmed Your store Account", "auth/email/confirm", user=user, token=token) flash("Check your email for the confirmation Email from us!") login_user(user, form.password.data) return redirect(url_for("main.index")) return render_template("auth/signup.html", form=form)
def deploy(): """Run deployment tasks.""" from flask_migrate import upgrade from app.model import Role, User # migrate database to latest revision upgrade() # create user roles Role.insert_roles() # create self-follows for all users User.add_self_follows()
def POST(self): data = web.input() user = User( username=data.username, email=data.email, password=data.password ) web.ctx.orm.add(user) web.ctx.orm.commit() if user.id and user.login() == 0: return web.seeother('/@'+user.username) return self.render('signup.html')
def on_get(self, req, res, user_id): session = req.context['session'] try: user_db = User.find_one(session, user_id) self.on_success(res, user_db.to_dict()) except NoResultFound: raise UserNotExistsError('user id: %s' % user_id)
def _check_logged_in(session_id): user = User.all().filter("session =", session_id).get() if user is None: return None else: return user[0]
def verify_password(email_or_token, password): if email_or_token == '': return False if password == '': g.current_user = User.verify_auth_token(email_or_token) g.token_used = True return g.current_user is not None user = User.query.filter_by(email = email_or_token).first() if user is None: return False g.current_user = user g.token_used = False return user.verify_password(password)
def process_login(self, req, res): email = req.params['email'] password = req.params['password'] session = req.context['session'] try: user_db = User.find_by_email(session, email) if verify_password(password, user_db.password.encode('utf-8')): self.on_success(res, user_db.to_dict()) else: raise PasswordNotMatch() except NoResultFound: raise UserNotExistsError('User email: %s' % email)
def test_user_from_json(self): result = User.from_json({ 'users': { 'id': 987, 'emailAddress': 'email_address', 'name': 'name', 'supplier': { 'supplierId': 1234, 'name': 'name' } } }) assert_equal(result.id, 987) assert_equal(result.email_address, 'email_address')
def on_post(self, req, res): session = req.context['session'] user_req = req.context['data'] if user_req: user = User() user.username = user_req['username'] user.email = user_req['email'] user.password = hash_password(user_req['password']).decode('utf-8') user.info = user_req['info'] if 'info' in user_req else None sid = uuid() user.sid = sid user.token = encrypt_token(sid).decode('utf-8') session.add(user) self.on_success(res, None) else: raise InvalidParameterError(req.context['data'])
def get(self, action='', account_key='', arg1=''): """ Serve up user related pages.""" if action == 'signup': self.set_template('templates/account/signup.html') #elif action == 'complete': elif action == 'confirm': self.set_template('templates/account/signupconfirm.html') user = User.all() user.filter("conf_key =", account_key) user.get() if user is None: error = "Could not locate your account information." self.error_message(error) self.add_template_value('title', "Cool Geek Jobs - Ooops!!!") else: u = user[0] logging.info(u.key()) self.add_template_value('title', "Cool Geek Jobs - Your Account is Activated") self.add_template_value('username', u.username.upper()) self.add_template_value('firstname', u.first.upper()) u.email_conf = True u.put() elif action == 'signin': self.set_template('templates/account/signin.html') elif action == 'edit': session_id = cgi.escape(self.request.get('session_id')) user = _check_logged_in(session_id) if user is None: self.set_template('templates/account/signin.html') self.error_message("SESSION EXPIRED") else: self.set_template('templates/account/useraccount.html') self.add_template_value("session_id", user.session) else: self.set_template('templates/account/signup.html') self.write_page()
def post(self, action="" , arg=""): """Handle posts""" if action == 'new': username = cgi.escape(self.request.get('username')) password = cgi.escape(self.request.get('password')) email = cgi.escape(self.request.get('email')) first = cgi.escape(self.request.get('firstname')) last = cgi.escape(self.request.get('lastname')) plan = cgi.escape(self.request.get('plan')) m1 = hashlib.sha1() # Pass in salt m1.update(BINSALT) m1.update(password) encrypt = b64encode(m1.digest()) logging.info(encrypt) conf_key = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(20)) user = User(username = username, password = encrypt, email = email, conf_key = conf_key, first = first, last = last, plan_type = plan, plan_date = datetime.datetime.now()) user.put() confirm_url = "http://www.coolgeekjobs.com/account/confirm/" + conf_key sender_address = "Cool Geek Jobs Alerts <*****@*****.**>" subject = "Please confirm your registration" body = """ Thank you for creating an account! Please confirm your email address by clicking on the link below: %s """ % confirm_url mail.send_mail(sender_address, email, subject, body) self.set_template('templates/account/signuppending.html') self.add_template_value('username', username.upper()) self.add_template_value('email', email.upper()) self.add_template_value('firstname', first.upper()) if last != '': self.add_template_value('lastname', last.upper()) planname = '' planfreq = '' if plan == 'weekly': planname = 'ONLY IF THE OPPORTUNITY IS RIGHT' planfreq = 'weekly' elif plan == 'daily': planname = 'JUST TESTING THE WATERS' planfreq = 'once a day' elif plan == 'hourly': planname = 'READY TO MAKE THE LEAP' planfreq = 'hourly' else: planname = 'GET ME OUTTA HERE!!!' planfreq = 'immediately' self.add_template_value('planname', planname) self.add_template_value('planfreq', planfreq) elif action == 'login': username = cgi.escape(self.request.get('username')) password = cgi.escape(self.request.get('password')) user = User.all() user.filter("username ="******"USERNAME AND/OR PASSWORD INCORRECT") else: u = user[0] m1 = hashlib.sha1() # Pass in salt m1.update(BINSALT) m1.update(password) encrypt = b64encode(m1.digest()) if encrypt != u.password: self.set_template('templates/account/signin.html') self.error_message("USERNAME AND/OR PASSWORD INCORRECT") else: session_id = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(20)) greeting = '' # Save login time u.last_login = datetime.datetime.now() u.session = session_id u.put() if u.first is not None: greeting = u.first.upper() else: greeting = u.username.upper() self.set_template('templates/account/useraccount.html') self.info_message("WELCOME BACK, " + greeting) self.add_template_value('session_id', session_id) self.add_template_value('links', _logged_in_menu(u.key().id())) self.write_page()
from app.model import User names = ['Louis', 'Tom', 'Mario', 'Tony', 'Montana', 'Don', 'Vito', 'Micheal', 'Tommy'] for name in names: user = User(name=name) user.save()
# Add roll field and convert create time to ISO date __author__ = 'tang' import os, sys from datetime import datetime model_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(model_path) from app.model import User, Section, Page users = User.find() for user in users: user.attr['roll'] = [] if not isinstance(user.attr['create_time'], datetime): user.attr['create_time'] = datetime.fromtimestamp(user.attr['create_time']) user.commit() pages = Page.find() for page in pages: if not isinstance(page.attr['create_time'], datetime): page.attr['create_time'] = datetime.fromtimestamp(page.attr['create_time']) if not isinstance(page.attr['modified_time'], datetime): page.attr['modified_time'] = datetime.fromtimestamp(page.attr['modified_time']) sections = Section.find() for section in sections: if not isinstance(section.attr['create_time'], datetime):