def post(self): self.set_header("Content-Type", "application/json") try: email = str(self.get_argument("email")) password = str(self.get_argument("password")) password2 = str(self.get_argument("password2")) except: self.write(json.dumps("邮箱、密码、确认密码均为必填项!")) return if password != password2: self.write(json.dumps("两次输入的密码不一致!")) return has_user = User.get_user_by_email(email) if not has_user: try: # TODO baitao.ji 改造为发送验证邮件后才插入数据库中的用户表 User.create_user("无名氏", email, password) self.write(json.dumps("OK")) except: self.write(json.dumps("保存用户时数据库超时,请稍后重试!")) else: self.write(json.dumps("已存在该邮箱, 请尝试其他邮箱或用该邮箱登录!")) return
def post(self): """ Login in with a Facebook account if the user has existed Otherwises, create a new user with information from Facebook """ args = fbUserParser.parse_args() fb_id = args['fbid'] fb_token = args['fbtoken'] if fb_id is None or fb_token is None: abort(400) # verify the user's facebook account using the facebook token fbuser_info = requests.get( 'https://graph.facebook.com/me?access_token=%s' % fb_token).json() if not fbuser_info.get('id') or fb_id != fbuser_info['id']: abort(406) fb_email = args['fbemail'] user = User.objects(email=fb_email).first() if user is None: user = User(email=fb_email, fb_id=fbuser_info['id']) user.save() token = user.generate_auth_token(expiration=360000) redis_store.set(str(user.id), token) return {'token': token}
def test_email_is_existed(): email = "*****@*****.**" result = User.email_is_existed(email) assert result == True email = "*****@*****.**" result = User.email_is_existed(email) assert result == False
def post(self): username = self.get_argument("username") password = self.get_argument("password") password_again = self.get_argument("password_again") next = self.get_argument('next', None) error = False if not (3 <= len(username) <= 15): error = True self.messages.error("用户名长度必须在 3-15 之间") if len(password) < 3: error = True self.messages.error("密码长度必须大于等于3") if User.exist(username): error = True self.messages.error("用户已存在!") if password != password_again: error = True self.messages.error("两次输入的密码不一致!") if not error: u = User.new(username, password) self.messages.success("账户创建成功!") self.redirect(url_for('signin') + (('?next=%s' % next) if next else '')) return self.render('user/signup.html')
def post(self): """ Sign up with Facebook account and return a token """ args = fbUserParser.parse_args() fb_id = args['fbid'] fb_token = args['fbtoken'] fb_email = args['fbemail'] if fb_id is None or fb_token is None or fb_email is None: abort(400) # verify the user's facebook account using the facebook token fbuser_info = requests.get( 'https://graph.facebook.com/me?access_token=%s' % fb_token).json() if not fbuser_info.get('id') or fb_id != fbuser_info['id']: abort(406) user = User(email=fb_email, fb_id=fb_id) try: user.save() except: return {'status': 'error', 'message': 'FBname has already existed'} token = user.generate_auth_token(expiration=360000) redis_store.set(str(user.id), token) return ({'status': 'success', 'token': token}, 201)
def save(self): id = int(self.get_argument('id',0)) name = self.get_argument('name') passwd = self.get_argument('password','') is_root = int(self.get_argument('is_root',0)) is_staff = int(self.get_argument('is_staff',0)) orgid = int(self.get_argument('orgid',0)) email = self.get_argument('email','') phone = self.get_argument('phone','') args = self.request.arguments role_ids = [self.get_argument(i,'') for i in self.request.arguments if i.startswith('role__')] role_ids = [int(i) for i in role_ids if i] print role_ids if id: u = User.mgr(ismaster=True).Q().filter(id=id)[0] else: u = User.new() u.name,u.passwd,u.is_root,u.is_staff,u.orgid = name,passwd,is_root,is_staff,orgid u.email,u.phone = email,phone u = u.save() id = u.id cur_roles = [i.role_id for i in UserRole.mgr().Q().filter(uid=id)] new_roles = [int(i) for i in role_ids] for i in [i for i in cur_roles if i not in new_roles]: ur = UserRole.mgr(ismaster=1).Q().filter(uid=id,role_id=i)[0] ur and ur.delete() for i in [i for i in new_roles if i not in cur_roles]: ur = UserRole.new() ur.uid,ur.role_id = id,i ur.save() self.json2dwz('200','closeCurrent','ulist',forwardUrl='user/list')
def authenticate(self, request): email = request.user_email validate_email(email) team_key = request.team_key user = User.find_user_by_email(email, team_key) if team_key: team_secret = request.team_secret validate_team_secret(team_secret) display_name = request.display_name image_url = request.user_image_url if not user: user = User.insert_user(email=email, username=display_name, account_type=team_key, image_url=image_url) community = Community.getCommunityFromTeamKey(team_key) UserRole.insert(user, community) elif (display_name != user.display_name) or (image_url != user.image_url): User.update_user(user=user, email=email, username=display_name, account_type=team_key, image_url=image_url) if not Community.authenticate(team_key, md5(team_secret)): raise endpoints.UnauthorizedException("Authentication failed. Team key and secret are not matched.") elif user.auth_source == AuthSourceType.ANNO: password = request.password validate_password(password) if not user: raise endpoints.NotFoundException("Authentication failed. User account " + email + " doesn't exist.") if not User.authenticate(email, md5(password)): raise endpoints.UnauthorizedException("Authentication failed. Email and password are not matched.") else: raise endpoints.ForbiddenException("Account for '%s' is Google or Facebook OAuth account." % email) return UserMessage(id=user.key.id(), display_name=user.display_name)
def test_user_deletes_reward(): reward_name = 'kisses' user = User('username', [Reward(reward_name, 1000)], [SnailTask('write an email')], [], todays_empty_purse) user.delete_reward(reward_name) tools.assert_false(user.has_reward_named(reward_name))
def post(self): args = fbUserParser.parse_args() fb_id = args['fbid'] fb_token = args['fbtoken'] if fb_id is None or fb_token is None: abort(400) fbuser_info = requests.get('https://graph.facebook.com/me?access_token=%s' %fb_token).json() if not fbuser_info.get('id') or fb_id != fbuser_info['id']: raise InvalidUsage('User info does not match',406) fb_email = args['fbemail'] user = User.objects(email=fb_email).first() if user is None: user = User(email=fb_email, fb_id=fbuser_info['id']) user.save() profile = Profile.objects(user=user).first() if profile is None: profile = Profile(user=user) profile.save() rongToken = rongcloudToken(profile.id) token = user.generate_auth_token() redis_store.set(str(user.id), token) return {'token': token, 'rongToken' : rongToken}
def dummy_data(): # Dummy test users for i in xrange(4): User.new_user( email='dummy{0}@dummy.com'.format(i), username='******'.format(i), password='******', management_api=pulse_management) users = User.query.all() # And some dummy queues dummy_queue = Queue(name='dummy-empty-queue', size=0, owner=users[0]) db_session.add(dummy_queue) db_session.commit() dummy_queue = Queue(name='dummy-non-empty-queue', size=config.warn_queue_size/5, owner=users[0]) db_session.add(dummy_queue) db_session.commit() dummy_queue = Queue(name='dummy-warning-queue', size=config.warn_queue_size + 1, owner=users[1]) db_session.add(dummy_queue) db_session.commit() dummy_queue = Queue(name='dummy-deletion-queue', size=int(config.del_queue_size * 1.2), owner=users[2]) db_session.add(dummy_queue) db_session.commit() # Test admin user User.new_user( email='*****@*****.**', username='******', password='******', management_api=pulse_management, admin=True) logger.info('Finished generating dummy data.')
def signup_base(): errors = {} try: email = request.form['email'] password = request.form['password'] try: confirm = request.form['confirm'] except KeyError: confirm = password if not password == confirm: errors['password'] = _(u"Inconsistent password twice.") if not validate_email(email): errors['email'] = _(u"please check your email address again") if len(password) < 6: errors['password'] = _(u"Your password is too short. At least 6 characters.") except KeyError: errors['KeyError'] = _(u'key error') if not errors: user = User.query.filter_by(email=email).first() if user: errors['email'] = _(u'this email has been used') else: user = User(email,pack_password(password)) user.commit() detail = UserDetail(user) detail.commit() login_user(user) refresh() return errors
def init_db(): from model.user import User from model.url import URL from model.cata import Cata from model.mod_log import ModLog from misc.const import d_cata, d_source # 创建表 db.create_tables([User, URL, Cata, ModLog]) # 新建用户 data = dict( user="******", name="admin", pwd=hashlib.md5('admin').hexdigest(), ) User.create(**data) # 创建交叉表 for k in d_cata.keys(): for k1 in d_source.keys(): c = Cata.select().where(Cata.cata == k, Cata.source == k1) if not c: d_ = dict( cata=k, source=k1, ) Cata.create(**d_)
def register(user_info, user_type): nuser = User(firstName = user_info['firstName'], lastName = user_info['lastName'], email = user_info['email'], password = user_info['password'], userType = user_type) try: nuser.save() return True except NotUniqueError: return False
def get(self): user = User() user.email = "" user.password = "" user.name="" user.password_confirm = "" return self.render('setting_add_user.html', user_name="", user=user, errors={})
def post(self): name = self.get_argument('name', '') email = self.get_argument('email', '') password = self.get_argument('password', '') if not name or len(name) > 15: self.render('join.html', error=111, name=name, email=email) return match = re.search(r'[\w.-]+@[\w.-]+', email) if not match: self.render('join.html', error=112, name=name, email=email) return if not password: self.render('join.html', error=110, name=name, email=email) return user = User.get_by_email(email) if user: self.render('join.html', error=113, name=name, email=email) return user = User.new(name, email) if user: user.update_password(encrypt(password)) else: self.render('join.html', error=114) self.set_secure_cookie('user', user.id, expires_days=30) self.redirect(self.get_argument('next', '/'))
def test_invalidate_cached_user(self): user = User(remote_url='http://microblog.brianschrader.com/feed') user.cache_user() self.assertEqual(user._status, dl.CACHED) self.assertEqual(user.username, 'sonicrocketman') user.invalidate_cached_user() self.assertEqual(user._status, dl.REMOTE)
def list(self): id = int(self.get_argument('id',0)) name = self.get_argument('name','') orgid = int(self.get_argument('orgid',0)) page = int(self.get_argument('pageNum',1)) psize = int(self.get_argument('numPerPage',20)) count = User.mgr().Q().count() page_count = (count+psize-1)/psize q = User.mgr().Q() id and q.filter(id=id) name and q.extra("name LIKE '%%%s%%'"%name) if orgid: org = Orgnization.mgr().one(orgid) q.extra("orgid in (%s)"%','.join([str(i.id) for i in org.children()])) users = q[(page-1)*psize:page*psize] for u in users: u.full_org_name = '-'.join([o.name for o in u.org_path()]) orgs = Orgnization.mgr().Q() self.render('user/user_list.html', name = name, orgid = orgid, page = page, psize=psize, count=count, page_count=page_count, users=users, orgs = orgs)
def post(self): password1 = self.get_argument('password1', '') password2 = self.get_argument('password2', '') username = self.current_user().username next = self.get_argument("next", "") error = False if len(password1) < 3 or len(password1) > 18: error = True self.messages.error('密码长度必须大于3小于18!') if len(password2) < 3 or len(password2) > 18: error = True self.messages.error('密码长度必须大于3小于18!') if password1 != password2: error = True self.messages.error('您输入的密码不一致!') if not User.exist(username): error = True self.messages.error('用户不存在!') if not error: User.update_pass(username, password1) self.messages.success('账户密码修改成功!') if next: return self.redirect(next) self.redirect('/') else: if next: return self.redirect(next) self.redirect('/')
def save_user_info(self, cmd_params): username = cmd_params['username']['value'] password = cmd_params['password']['value'] experience = cmd_params['experience']['value'] level = cmd_params['level']['value'] user = User(username, password) dbconn = DBConnection(conf.DB_USER) cursor = dbconn.get_cursor() uid = user.get_uid() user_info = None if uid in cursor.keys(): user_info = cursor[uid] if not user_info: user_info = user.pack_user_info() user_info['experience'] = experience user_info['level'] = level cursor[uid] = user_info dbconn.write_back(cursor) reply_info = [('error', False, TYPE.BOOLEAN)] return reply_info
def register_handler(): username = request.form['username'] password = request.form['password'] email = session['email'] errors = [] if not re.match('^[a-z0-9]+$', username): errors.append("The submitted username contains non-alphanumeric characters") if User.query.filter(User.email == email).first(): errors.append("A user with the same email already exists") if not User.strong_password(password): errors.append("Your password must contain a mix of letters and numerical characters and be at least 6 characters long") # Checking if a user exists in RabbitMQ OR in our db try: pulse_management.user(username=username) in_rabbitmq = True except PulseManagementException: in_rabbitmq = False if in_rabbitmq: errors.append("A user with the same username already exists in Pulse") if User.query.filter(User.username == username).first(): errors.append("A user with the same username already exists in our database") if errors: signup_error = "{0}.".format(', '.join(errors)) return render_template('register.html', email=email, signup_error=signup_error) user = User.new_user(email=email, username=username, password=password, management_api=pulse_management) db_session.add(user) db_session.commit() return render_template('confirm.html')
def POST(self): data = web.input() username, password, email = data.username, data.password, data.email user = User() if user.register(username, password, email): return render.login() return render.register()
def create(request): ''' if(request.method != 'POST'): return HttpResponse("Invalid create request", status=503) json_data = simplejson.loads(request.raw_post_data) ''' json_data = request.REQUEST # Getting all the request parameters as json string print json_data ' Check to see if all params have empty values' jsondataempty=True for val in json_data.values(): if val: jsondataempty=False if jsondataempty: ret = { 'success':False, 'id':'', 'error':'All input fields are empty' } else: u = User() for name in json_data: # TODO: Add validation of attribute names and values u.__dict__[name] = json_data[name] u.save() ret = { 'success':True, 'id':str(u._id) } return HttpResponse(simplejson.dumps(ret),"application/json")
def __init__(self): db = Database('database') if db .root is None: root = Persistent() root.list_of_users = [] db.elect (root) transaction.commit() checkout(db.root) self.list_of_users = db.root.list_of_users # Creating a user default to make easy the development user = User('Fulano', '*****@*****.**', 'pwd', "uid") document = Document("My document", ".txt", "I think to myself... what a wonderful world!", "uid", user.folder.id) document.id = "did" user.folder.id = "fid" user.add_document(user.folder.id, document) db.root.list_of_users.append(user) db.root.list_of_users = self.list_of_users transaction.commit() checkout(db .root) self.list_of_users = db .root.list_of_users else: self.list_of_users = db.root.list_of_users super(UserRepository, self).__init__()
def get(self): users = User.all().fetch(None) emails = [user.email for user in User.all()] current_user = util.get_user_from_session() template_values = {'emails': emails, 'current_user': current_user.email if current_user else None} path = 'templates/list_users.html' self.response.out.write(template.render(path, template_values))
def post(self): username = self.get_argument('username', '') email = self.get_argument('email', '') password = self.get_argument('password', '') if not username or len(username) > 15: self.render('home/register.html', error=111, username=username, email=email) return match = re.search(r'[\w.-]+@[\w.-]+', email) if not match: self.render('home/register.html', error=113, username=username, email=email) return if not password: self.render('home/register.html', error=110, username=username, email=email) return user = User.get_by_username(username) if user: self.render('home/register.html', error=112, username=username, email=email) return user = User.get_by_email(email) if user: self.render('home/register.html', error=114, username=username, email=email) return #走代理获取ip方式 reg_ip = self.request.headers['X-Real-Ip'] user = User.new(username, email, password, reg_ip) if user: self.set_secure_cookie('user_id', str(user.user_id), expires_days=30) self.redirect(self.get_argument('next', '/')) else: self.render('home/register.html', error=115)
def pull_user_info(openid, web_access_token=None): if web_access_token: pull_user_info_url = wxconfig.pull_user_info_url.format(web_access_token, openid) http_client = AsyncHTTPClient() response = yield http_client.fetch(pull_user_info_url) logging.debug(response.body.decode()) user_dict = json.loads(response.body.decode()) user = dict_to_model(User, user_dict, ignore_unknown=True) else: user = User(openid='openid') user_id = None try: _user = dbutil.do(User.get, User.openid == openid) user_id = _user.get_id() exists = True except DoesNotExist: exists = False if exists: assert user_id user.set_id(user_id) user.updatetime = datetime.datetime.now() else: user.createtime = datetime.datetime.now() yield dbutil.do(user.save) user = yield dbutil.do(User.get, User.openid == openid) return model_to_dict(user)
def get_user_from_request(user_id=None, user_email=None, team_key=None): user = None if user_id: user = User.get_by_id(user_id) elif user_email: user = User.find_user_by_email(user_email, team_key) return user
def test_user_deletes_task(): task_name = 'write an email' user = User('username', [Reward('kisses', 1000)], [SnailTask(task_name)], [], todays_empty_purse) user.delete_task(task_name) tools.assert_false(user.has_task_named(task_name))
def _process_users(self, session, **kwargs): modified_voters = set() new_user = None if "new_voter" in kwargs and kwargs["new_voter"]: new_user = User(name=kwargs["new_voter"]) new_user.put() user_by_session = UserBySession(user=new_user, session=session) user_by_session.put() voter_keys = [] if "voter_key" in kwargs: voter_keys = [kwargs["voter_key"]] if isinstance(kwargs["voter_key"], list): voter_keys = voter_keys[0] if "voter_name" in kwargs and not isinstance(kwargs["voter_name"], list): kwargs["voter_name"] = [kwargs["voter_name"]] for i in range(len(voter_keys)): voter = User.get(voter_keys[i]) voter.name = kwargs["voter_name"][i] voter.put() modified_voters.add(voter) return (new_user, modified_voters)
def init_user_info(): """Initialize user info to db.""" name = "suwen" password = salt_password("xxxxxx") email = "*****@*****.**" user = User(name=name, password=password, email=email) user.insert()
def Edit(self): # 验证 token = self.Post('token') msg = AdminToken.Verify(token, request.path) if msg != '' : return self.GetJSON({'code':4001, 'msg':msg}) tData = AdminToken.Token(token) # 参数 passwd = self.Post('passwd') passwdNew = self.Post('passwdNew') if passwd==passwdNew : return self.GetJSON({'code':4000, 'msg':'不能与原密码相同!'}) if not Safety.IsRight('passwd', passwd) or not Safety.IsRight('passwd', passwdNew) : return self.GetJSON({'code':4000, 'msg':'密码为6~16位!'}) # 数据 model = User() model.Columns('id') model.Where('id=%s AND password=%s', str(tData['uid']), Hash.Md5(passwd)) uData = model.FindFirst() if not uData : return self.GetJSON({'code':4000, 'msg':'当前密码错误!'}) model.Set({'password':Hash.Md5(passwdNew)}) model.Where('id=%s', str(tData['uid'])) if not model.Update() : return self.GetJSON({'code':5000, 'msg':'修改失败!'}) # 返回 return self.GetJSON({'code':0, 'msg':'成功'})
def post(self): args = user_parser.parse_args() user = User(username=args.username, password=args.password, email=args.email, firstName=args.firstName, lastName=args.lastName, phone=args.phone) # TODO mejorar la forma de generar el hash. # sobreescribiendo el constructor falla al validar el password. # no pude sobreescribir el save... user.generate_hashed_password() user.save() mailService.createUser(user) log.info("Crea nuevo Usuario: {'username':'******'}" % user.username) return generate_token(user), 201
def main(): """ allows to append User's payments and clear them :return: nothing """ read = serialize_type()[0] write = serialize_type()[1] main_user = read() if main_user is None: main_user = User(0.00) while True: key = get_key() if key == '1': account = View.input_accounting() main_user.add_payment(account) elif key == '2': main_user.clear_payments() main_user.set_money(0.00) elif key == '3': write(main_user) return None else: print("You've entered incorrect value")
def post(self): # email = request.form.get('email') username = request.form.get('username') password = request.form.get('password') if username is None or password is None: abort(400) # missing arguments user = User(username=username) user.hash_password(password) try: user.save() except: return { 'status': 'error', 'message': 'username has already existed' } return ({'username': user.username}, 201)
def getFromUser(self, u): con = None try: uid = u.id con = lite.connect('databases/' + self.file) con.row_factory = lite.Row cur = con.cursor() cur.execute( "SELECT * FROM " + self.core_table + "_flags WHERE flagger_id=?", (uid, )) data = cur.fetchall() nw_data = [] for row in data: row = dict(row) row["flagger"] = muser_User.from_id(row["flagger_id"]) nw_data.append(row) return nw_data except lite.Error as e: return False finally: if con: con.close()
def get_users_list(self): if self.user_cache is None: wd = self.app.wd self.open_homepage() self.user_cache = [] for element in wd.find_elements_by_name("entry"): td = element.find_elements_by_tag_name("td") id = td[0].find_element_by_name("selected[]").get_attribute( "value") last_name = td[1].text first_name = td[2].text address = td[3].text all_emails = td[4].text all_phones = td[5].text self.user_cache.append( User(id=id, lastname=last_name, firstname=first_name, address=address, all_emails_from_home_page=all_emails, all_phones_from_home_page=all_phones)) return list(self.user_cache)
def register(): user_name = request.json.get("user_name") password = request.json.get("password") mobile = request.json.get("mobile") sms_code = request.json.get("sms_code") if not all([user_name, password, mobile, sms_code]): return render_failed("", enums.param_err) # ts_code = ts.get(enums.register_sms_key + mobile) # if not ts_code: # return render_failed("", enums.sms_code_valid) # if ts_code.decode() != sms_code: # return render_failed("", enums.sms_code_err) exist_user = session.query(User).filter(User.mobile == mobile).first() if exist_user: return render_failed("", enums.mobile_exist) user = User( user_name=user_name, mobile=mobile, password=code.generate_md5(current_app.config.get("SALT") + password)) session.add(user) session.commit() return render_success({"X-AUTH-TOKEN": code.encode_auth_token(user.id)})
def register_user(verifying_code, telephone, name, username, password, mobile, role_type, fk_location_code, fk_plate): """ 注册 :param verifying_code: :param telephone: :param name: :param username: :param password: :param mobile: :param role_type: :param fk_location_code: :param fk_plate: :return: cs.OK """ verifying = rget(get_sms(telephone)) if not verifying or verifying != verifying_code: return cs.VERIFYING_ERROR, None user = User.query.filter_by(username=username).first() if user: return cs.USER_EXIST, None print role_type print cs.USER_ROLE_TYPE.keys() if int(role_type) not in cs.USER_ROLE_TYPE.keys(): return cs.AUTH_ERROR, None if int(role_type) in [cs.USER_ROLE_INFO[u"承运商"], cs.USER_ROLE_INFO[u"商家"]]: fk_location_code = None m2 = hashlib.md5() m2.update(password) password = m2.hexdigest() try: user = User(name, username, password, mobile, role_type, fk_location_code, fk_plate) db.session.add(user) db.session.commit() return cs.OK, None except: logger.error('register user error:{}'.format(traceback.format_exc(), )) raise finally: db.session.remove()
def validate_credentials(): body = request.get_json() if body is None: abort(400) user = User(body) # the result is a user on success # this will delete the token from ram # (as posted user is not used and db user doesn't store token) result = Connector.validate_hash(user) if result is None: abort(403) elif result == -1: abort(404) elif isinstance(result, User): # generate jwt token return Auth.gen_token(result), 200 else: abort(422)
def init(): for role, access in ROLES.items(): res = [] perm = [] for a in access: if(a["RESOURCE"] not in RESOURCE_DB): raise Exception("Resource not found in db") resource = RESOURCE_DB[a["RESOURCE"]] permission = tuple(a["ACCESS"]) res.append(resource) perm.append(permission) r = Role(role, res, perm) ROLE_DB[role] = r for user in USERS: roles = [] for role in USERS[user]: if(role not in ROLE_DB): raise Exception("Role not found") roles.append(ROLE_DB[role]) u = User(user, roles) USER_DB[user] = u
def setUp(self): app.config['TESTING'] = True app.config['DEBUG'] = False self.app = app.test_client() build_user() build_positions() build_trades() mike = User(**{ "user_name": "mikebloom", "password": "******", "real_name": "Mike Bloom", "balance": 0.0 }) mike.hash_password("password") mike.api_key = "11111111111111111111" mike.save() return app
def create(profile, user): steamid = profile['steamid'] name = profile['personaname'] avatar = profile['avatar'] recently_played_games = user_data.recently_played_games(steamid) genres = [] for id in recently_played_games: genres.extend(game_factory.get_or_create(id).genres) friend_genre_scores = score.genre_scores(genres) user_genre_scores = json.loads(user.genre_scores) compatibility_score = score.compatibility_percentages( user_genre_scores, friend_genre_scores) friend_user = User.get_or_insert( key_name=steamid, games=recently_played_games, name=name, avatar=avatar, genre_scores=json.dumps(friend_genre_scores)) Friend(key_name=steamid, parent=user, user=friend_user, compatibility_score=compatibility_score).put()
def get_users(self, whereclause=None): if whereclause is None: whereclause = "" result = {} cnxn = pyodbc.connect(self.constr_lora) cursor = cnxn.cursor() cursor.execute("SELECT [Opus_id], \ [Uuid], \ [UserId], \ [Email], \ [Phone], \ [Updated], \ [WorkMobile] \ FROM [dbo].[Users] \ " + whereclause + ";") for row in cursor.fetchall(): opus_id = row.Opus_id usr = User(opus_id, row.Uuid, row.UserId, row.Email, row.Phone, row.Updated, row.WorkMobile) result[int(opus_id)] = usr return result
def get_user_list(self): if self.user_list_cache is None: wd = self.app.wd self.app.open_home_page() self.user_list_cache = [] for row in wd.find_elements_by_name("entry"): cells = row.find_elements_by_tag_name("td") firstname = cells[2].text lastname = cells[1].text address = cells[3].text id = cells[0].find_element_by_tag_name("input").get_attribute( "value") all_phones = cells[5].text all_emails = cells[4].text self.user_list_cache.append( User(firstname=firstname, lastname=lastname, address=address, user_id=id, all_phones_from_home_page=all_phones, all_emails_from_home_page=all_emails)) return list(self.user_list_cache)
def log_in(): username = request.form['username'] password = request.form['password'] user = mysql.get_user(username) if user: if not user['enable']: return jsonify({'success': False, 'msg': 'User has been banned! Please contact administrator.'}), 403 # 如果用户的TJUPT账户被封禁,则将Reseed账户同时封禁 if user['tjupt_id']: user_active = check_id_tjupt(user['tjupt_id']) if not user_active: mysql.ban_user(user['id']) return jsonify({'success': False, 'msg': 'User has been banned! Please contact administrator.'}), 403 if bcrypt.checkpw(password.encode('utf-8'), user['passhash'].encode('utf-8')): return jsonify({'success': True, 'msg': 'Success~', 'token': User(user).get_auth_token()}) else: return jsonify({'success': False, 'msg': 'Invalid username or password!'}), 403 else: return jsonify({'success': False, 'msg': 'Invalid username or password!'}), 403
def post(self): post_data = {} for key in self.request.arguments: ##从请求的参数中获取关键字 key post_data[key] = self.get_arguments(key)[0] ##post_data[key]?? 返回值是什么? 列表 self.get_arguments(key)[0] print(post_data) respon = None if post_data['roletype'] == '0' :#学生 ## 如果发送的数据 中的某个关键字 roletype post_data["roletype"],post_data["name"] ur = Dal_User().getUserByAttr('id',(int)(post_data['id']))## 声明一个ur列表 使用一个方法 传入两个参数 目的是查看是否已经存在 if len(ur) == 0: ##说明还没有注册,下一步就是注册 um = User(id=(int)(post_data['id']), sname= post_data['sname'], fun_list= None,create_org_list =None,create_act_list=None, join_act_list =None,join_org_list =None,befun_list =None, sex =post_data['sex'],grade =post_data['grade'], college =post_data['college'],apply_org_list =None, apply_act_list = None,apply_create_org_list = None, apply_create_act_list = None) Dal_User().addUser(um) respon = {'errorcode':configs_error['success'], 'id':um.id} else: respon = {'errorcode':configs_error['register_already']} elif post_data['roletype'] == '1':#社管 off = Dal_Officer().getOfficerByAttr('id',(int)(post_data['id'])) if len(off) == 0: um = Officer(id=(int)(post_data['id']), name= post_data['name'], title= post_data['title'] ) Dal_Officer().addOfficer(um) respon = {'errorcode':configs_error['success'], 'id':um.id} else: respon = {'errorcode':configs_error['register_already']} else: respon = {'errorcode':configs_error['paramerror']} respon_json = json.dumps(respon) #respon_json = tornado.escape.json_encode(respon) ##在网页中需要加入响应头 self.set_header("Access-Control-Allow-Origin","*") self.write(post_data)
def post(self): email = self.get_argument('email', '') user_name = self.get_argument('user_name', '') password = self.get_argument('password', '') password_confirm = self.get_argument('password_confirm', '') user = User() user.email = email user.name = user_name user.password = password user.password_confirm = password_confirm user_id = user.create() if not user_id: return self.render('register.html', user_name="", user=user, errors=user.errors) #return self.send_error_json(user.errors) else: self.redirect('/login')
def post_user(): '''添加一个用户''' now = datetime.datetime.now() # args_list = [ ('password', 'str', 'must'), ('username', 'str', 'must'), ('email', 'str', 'default', ''), ('mobile', 'str', 'default', ''), ('status', 'int', 'default', 1), ('type', 'int', 'default', 1), ('login_time', 'datetime', 'default', now.strftime(DATETIME_FMT)), ('regi_time', 'datetime', 'default', now.strftime(DATETIME_FMT)), ('login_address', 'str', 'default', request.remote_addr), ] args = build_args(request.values, args_list) user = User(**args) current_app.dbsess.add(user) current_app.dbsess.commit() return output()
def login(): if request.method == "GET": return redirect(url_for("index")) form = LoginForm() if form.validate_on_submit(): try: back = redirect( url_for(form.back.data, **loads(sub("( u)?'", "\"", form.args.data)))) except (BuildError, ValueError): back = redirect(url_for("index")) if g.user and g.user.is_authenticated: return back user = User.get(form.username.data) if user and user.validate_password(form.password.data): login_user(user, remember=True) return back return render_template("error.html", heading="Login failed!", text="Wrong user name or password.", back=form.back.data, args=form.args.data)
def handler_registry(form): if not ('login' in form and 'password' in form and 'email' in form): raise InternalServerError('Переданы неверные параметры') if form['login'] in app.config['SERVICE_NAMES']: raise InternalServerError( 'Имя пользователя недоступно для регистрации') if len(form['email']): find = User.objects(Q(login=form['login']) | Q(email=form['email'])).first() else: find = User.objects(Q(login=form['login'])).first() if not find: user = User(login=form['login'], password=User.get_password(form['password']), key=form['login']) if len(form['email']): user.email = form['email'] user.save() return handler_login(form) else: if find.login == form['login']: raise InternalServerError('Этот логин уже используется') elif len(form['email']) and find.email == form['email']: raise InternalServerError('Этот e-mail уже используется')
def fetch_notif_of_metion(user_id, last_mention_id=b'\x00'): # 某某 在文章 某某某 中@了你: XXXXXX # c2 是 user_id 的原评论,c 是回复评论的评论 from .mention import Mention item_lst = Mention.select().where(Mention.who == user_id, Mention.id > last_mention_id) # 懒得写sql查询了 user_ids = [] id2user = {} for m in item_lst: user_ids.append(m.user_id) for u in User.select().where(User.id.in_(user_ids)): id2user[u.id] = u def get_nickname(uid): if uid == 0: return '系统' u: User = id2user.get(uid, None) if u is None: return return u.nickname def wrap(i: Mention): return { 'type': NOTIF_TYPE.BE_MENTIONED, 'time': i.time, 'mention': { 'id': i.id, 'user': { 'id': i.user_id, 'nickname': get_nickname(i.user_id) }, 'related_id': i.related_id, 'related_type': i.related_type, 'data': i.data, } } return map(wrap, item_lst)
def get(self): session = get_current_session() company_id = str(self['company_id']) c = Company.get_by_id(int(company_id)) if not c: self.write('no company') return user_id = session['me_email'] path = 'expose_social_data.html' user = User.get_by_key_name(str(user_id)) breadcrumb_idx = 3 template_values = { 'name': user.name, 'company_id': company_id, 'github_auth_url': '/users/data/github/update?company_id=' + company_id, 'angellist_auth_url': '/users/data/angellist/update?company_id=' + company_id, 'linkedin_auth_url': '/users/data/linkedin/update?company_id=' + company_id, 'dribbble_auth_url': '/users/data/dribbble/update?company_id=' + company_id, 'odesk_auth_url': '/users/data/odesk/update?company_id=' + company_id, 'breadcrumbs': registration_breadcrumbs[startups], 'breadcrumb_idx': breadcrumb_idx, 'breadcrumbs_len': len(registration_breadcrumbs[startups]), 'breadcrumb': registration_breadcrumbs[startups][breadcrumb_idx - 1], 'progress': (100 / len(registration_breadcrumbs[startups])) * breadcrumb_idx } self.write(self.get_rendered_html(path, template_values), 200)
def get_user_list(self): if self.user_cache is None: wd = self.app.wd self.open_home_page() self.user_cache = [] # for element in wd.find_elements_by_css_selector("tr"): for element in wd.find_elements_by_name("entry"): cells = element.find_elements_by_tag_name("td") last = cells[1].text user = cells[2].text address = cells[3].text id = element.find_element_by_name("selected[]").get_attribute( "value") all_phones = cells[5].text all_email = cells[4].text self.user_cache.append( User(last_name=last, username=user, id=id, address=address, all_phone=all_phones, all_email=all_email)) return (self.user_cache)
def login(): a = {} if request.method == 'POST' and 'username' in request.form and 'password' in request.form: # Create variables for easy access username = request.form['username'] password = request.form['password'] info = db.session.query(User).filter(User.user_name == username).one() if User.verify_hash(password, info.password_hash): print('user exist : ', info.user_name) print('category ', info.category) # If account exists in accounts table in out database if info: # Create session data, we can access this data in other routes print("in info check") session['loggedin'] = True session['id'] = info.id session['username'] = info.user_name # Redirect to home page return {'status': '0', 'category': info.category} else: # Account doesnt exist or username/password incorrect return {'status': '1', 'category': info.category} return render_template("homepage.html")
def import_user(): ''' from a file split by \t import User 深圳欣沣晟通讯_acc 145605 ''' fn = open("/home/zongkai/logstat_mysql/logstat/tools/import_user.txt") for i in fn.readlines(): line = i.strip().split('\t') name = line[0] passwd = line[1] try: u = User.new() u.name = name u.passwd = passwd u.is_root = 0 u.is_staff = 0 u.orgid = 18 u.email = name + "@163.com" #print u #u.save() except: print u
def activate_user(admin, username, timestamp): user = User.objects(login=username).first() if user.rate: user.timestamp += int(timestamp) else: user.timestamp = int(time()) + int(timestamp) user.rate = 1 user.save() Session.objects(data__login=user.login).update( **dict(data__timestamp=user.timestamp, data__rate=user.rate)) if app.config['SEND_ACTIVATE']: unit = get_unit_time(timestamp) send( app.config['SMTP_LOGIN'], 'Активация профиля на {0}'.format(app.config['TITLE']), str( render_template('mail/activate.html', admin=admin, username=username, unit=unit['key'], time=unit['value'], date=datetime.fromtimestamp(int( time())).strftime('%Y-%m-%d %H:%M:%S'))))
def login(request): if request.method == 'GET': return render_to_response('nmaptoolview/login.html', {'data': ''}) else: username = request.POST.get('username', '') password = request.POST.get('password', '') result, username, role, power = usercontrol.validuser( username, password) if result: response = render_to_response('nmaptoolview/mainpage.html', { 'data': '用户名和密码成功', 'username': username }) loginuser = User(result, username, password, role, power) #将username写入浏览器cookie,失效时间为3600 webtool.setCookies(response, loginuser, 3600) return response else: return render_to_response('nmaptoolview/login.html', {'data': '用户名或密码错误'})
def request_loader(request): user_token = request.headers.get('X-Auth-Token') if user_token is None: return try: # https://firebase.google.com/docs/auth/admin/verify-id-tokens?hl=ja#verify_id_tokens_using_the_firebase_admin_sdk firebase_auth_info = auth.verify_id_token(user_token) except InvalidIdTokenError: return user_id = firebase_auth_info['uid'] repository = UserRepository() stored_user = repository.get_by_id(user_id) if stored_user is not None: return stored_user # Register DB a new user. new_user = User( user_id=user_id ) repository.insert(new_user) return new_user
def register(): error = None if request.method == "POST": username = request.form["username"] password = request.form["password"] email = request.form["email"] if username and password and email: params = { "username": username, "password": sha1(password), "email": email } print params user = User().insert(params) print user if user: return redirect(url_for("login")) else: error = u"你杯具了,注册失败" else: error = u"亲,请认真填写注册信息哦,可不带这么偷懒的" return render_template("register.html", error=error)
def run(self): # if not self._event.isInChannel('Megamoji'): # return # connect to MongoDB, change the << MONGODB URL >> to reflect your own connection string # client = MongoClient(os.environ.get('MONGO')) # db=client.slack # event = self._event.event() # if 'blocks' in event: # del(event['blocks']) # event['_id'] = event['client_msg_id'] # print(event) # db.events.insert_one(event) # messages = db.events.find({"channel": "CDU145F08"}) # for m in messages: # print(m) # Issue the serverStatus command and print the results return if not self._event.isFromABot(): user = User(self._event) return