def admins(): if request.method == 'POST': form = AdminForm(request.form) if form.validate(): admin = Admin() form.populate_obj(admin) admin.pw_hash = bcrypt.generate_password_hash(form.password.data) g.db.session.add(admin) g.db.session.commit() login_user(get_admin(g.db, admin.email)) flash('Welcome to xAPI Scavenger Hunt', 'success') logger.info( 'Admin registration form was submitted successfully for %s', admin.email) return make_response(render_template( 'settings.html', form=SettingForm())) logger.info( 'Admin registration form was submitted with' ' invalid information. Errors: %s', form.errors) flash( 'There was an error creating your admin profile.' ' Please try again.', 'warning') return render_template( 'homepage.html', form=form, display_login_link=True) return login()
def login(email, password): """管理员登录 当验证登录信息正确后,更新用户上次登录时间为系统当前时间 :param email: Email :type: string. return: : Admin Obj """ admin = Admin.query.filter(Admin.email == email).first() all_admin = Admin.query.all() try: assert all_admin != [] # 管理员status若不为1,则表示不处于活跃状态,则不允许登录 if admin and admin.status != '1': return None if admin and admin.check_password(password): admin.last_login = datetime.now() admin.update() return admin except: if not all_admin: admin = Admin('admin', email, password) admin.save() print '没有管理员,添加第一个管理员' return True print '找不到用户' return None
def POST(self): data = web.input(req='') req = data.req if req == "email": try: result = Admin.getBy(username=self.session.username) web.header('Content-Type', 'application/json') if result: return json.dumps({'email': result.email}) else: return json.dumps({'err': '没有找到匹配的用户'}) except Exception as err: web.header('Content-Type', 'application/json') return json.dumps({'err': '出现错误: ' + str(err)}) elif req == "submit": web.header('Content-Type', 'application/json') try: if data.nickname == "": return json.dumps({"err", "请输入昵称"}) if data.email == "email": return json.dumps({'err', "请输入邮箱"}) person = Admin.getBy(username=self.session.username) person.nickname = data.nickname person.email = data.email person.update() self.session.nickname = data.nickname return json.dumps({'success': "个人资料更新成功"}) except Exception as err: return json.dumps({'err': "出现错误: " + str(err)}) else: return web.Forbidden()
def post(self): # save the admin newAdminEmail = self.request.get("email") newAdmin = Admin(parent = PARENT_KEY, email = newAdminEmail) newAdmin.put() self.redirect(self.request.referer)
def add_user(): default_admin = Admin(username='******', email='*****@*****.**', password='******', phone_no='7777777777', postal_address='1, Beverly Park Circle, California') username = input("username: "******"email: ") password = input("password: "******"phone no: ") postal_address = input("postal address: ") role = input("role: ") res = default_admin.add_user(username=username, email=email, password=password, phone_no=phone_no, postal_address=postal_address, role=role, session_id=None) print('User Added') return res
def init_db(): from models import Admin admin = { 'email': Config.ADMIN_USER['login'] } exists = Admin.find_one(admin) if not exists: u = Admin(admin) u.encrypt_password(Config.ADMIN_USER['password'])
def init(username, password): print('Initializing the database...') db.create_all() admin = Admin.query.first() if admin is not None: print('The administrator already exists, updating...') admin.username = username admin.set_password(password) else: print('Creating the temporary administrator account...') admin = Admin(username='******', blog_title="Flaskblog", blog_sub_title="No,I am the real thing", name="Miro", about="I am a fun guy....") admin.set_password(password) db.session.add(admin) category = Category.query.first() if category is None: print('Creating the default category...') category = Category(name='Default') db.session.add(category) db.session.commit() print('Done.')
def init(username, password): click.echo('Initializing the database...') db.create_all() admin = Admin.query.first() if admin is not None: click.echo('The administrator already exists, updating...') admin.username = username admin.set_password(password) else: click.echo('Creating the temporary administrator account...') admin = Admin(username=username, blog_title='Bluelog', blog_sub_title="No, I'm the real thing.", name='Admin', about='Anything about you.') admin.set_password(password) db.session.add(admin) category = Category.query.first() if category is None: click.echo('Creating the default category...') category = Category(name='Default') db.session.add(category) db.session.commit() click.echo('Done.')
def create_user(): """创建用户 --- tags: - 用户 security: - api_key: [] responses: 200: description: 获取成功 schema: type: object properties: code: type: int data: type: array $ref: '#/definitions/Module' message: type: string examples: code: 0 data: [{}, {}] message: 'success' """ data = json.loads(request.data) Admin.create(**data) return success()
def admins(): if request.method == 'POST': form = AdminForm(request.form) if form.validate(): admin = Admin() form.populate_obj(admin) admin.pw_hash = bcrypt.generate_password_hash(form.password.data) g.db.session.add(admin) g.db.session.commit() login_user(get_admin(g.db, admin.email)) flash('Welcome to xAPI Scavenger Hunt', 'success') logger.info( 'Admin registration form was submitted successfully for %s', admin.email) return make_response( render_template('settings.html', form=SettingForm())) logger.info( 'Admin registration form was submitted with' ' invalid information. Errors: %s', form.errors) flash( 'There was an error creating your admin profile.' ' Please try again.', 'warning') return render_template('homepage.html', form=form, display_login_link=True) return login()
def ajax_admin_add(request): #需要登录才可以访问 if not request.session.get("sess_admin", False): return commons.res_fail(1, "需要登录才可以访问") name = request.REQUEST.get("name") pwd = request.REQUEST.get("pwd") pwd2 = request.REQUEST.get("pwd2") if name == "": return commons.res_fail(1, "用户名不能为空") if pwd == "": return commons.res_fail(1, "密码不能为空") if pwd != pwd2: return commons.res_fail(1, "确认密码不正确") total = Admin.objects.filter(name = name).count() if total > 0: return commons.res_fail(1, "该管理员已存在") admin = Admin( name = name, pwd = pwd, add_time = int(time.time()) ) admin.save() return commons.res_success("添加成功", json.loads(admin.toJSON()))
def test_get_by_id(self): """Get user by ID.""" user = Admin(username='******', password='******') user.save() retrieved = Admin.query.get_or_404(user.id) assert retrieved == user
def admin_remove_user(): if 'userid' not in session: return redirect('/login') adminStatus = Admin.query.get(session['userid']) if adminStatus and session['userid'] == 1: Admin.delete_admin_user(request.form) return redirect('/admin')
def fake_admin(): admin = Admin(username='******', blog_title='江湖人称蛋总', blog_subtitle='敬畏技术,谦卑而行', name='王', about='ssssss') admin.set_password('password') db.session.add(admin) db.session.commit()
def initialize(): try: user = input('请输入初始化用户名:').strip() pwd = input('请输入初始化密码:').strip() obj = Admin(user,pwd) obj.save() return True except Exception as e: print(e)
def admin_add_user(): if 'userid' not in session: return redirect('/login') adminStatus = Admin.query.get(session['userid']) if adminStatus and session['userid'] == 1: Admin.add_admin_user(session['userid'], request.form['new_admin_email']) return redirect('/admin')
def save_user(username, userdata): admin = Admin.query.filter_by(uid=username).first() if admin is None: admin = Admin(username, userdata['name'].decode("utf-8"), userdata['email'].decode("utf-8")) db.session.add(admin) else: admin.name = userdata['name'].decode("utf-8") admin.email = userdata['email'].decode("utf-8") db.session.commit() return admin
def GET(self): admins = Admin.getAll() operator = Admin.getBy(username=self.session.username) print admins for i in range(len(admins)): # role = 0 为最高权限, role越大, 权限越低 if admins[i].username == operator.username: index = i admins[i].deletable = (admins[i].role > operator.role) admins.pop(index) print admins return render.admin.users(page=self.page, session=self.session, admins=admins)
def before_scenario(context, scenario): db.drop_all() db.create_all() admin = Admin() admin.first_name = uuid.uuid4().hex admin.last_name = uuid.uuid4().hex admin.email = "{}@example.com".format(uuid.uuid4().hex) admin.password = uuid.uuid4().hex db.session.add(admin) db.session.commit() context.admin = admin print context.admin.email, context.admin.password
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = Admin(login=form.login.data, email=form.email.data) user.set_password(form.password.data) config.db.session.add(user) config.db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('login')) return render_template('registration.html', title='Register', form=form)
def add(name, email, password): """添加管理员 :param name: 用户名 :type: string. :param email: Email :type: string. :param password: 登录密码 :type: string. :return: : True """ if not Admin.query.filter(Admin.email == email).first(): admin = Admin(name, email, password) admin.save() return True else: return False
def add_keywords(update, context): try: keyword_sent_list = update.effective_message.text.split('\n') except ValueError: update.message.reply_text('ورودی اشتباه') return ADD_WORDS admin = Admin.get_by_username(update.effective_message.from_user.username) for keyword in keyword_sent_list: if not keyword in Admin.get_keywords(admin.username): Keyword(name=keyword, admin_id=admin.id).add() return ADD_WORDS
def fetchAllAdminExceptMe(email): cursor = mysql.connection.cursor() cursor.execute("select email, name from admin where email!='%s'" % (email)) adminListRaw = cursor.fetchall() mysql.connection.commit() cursor.close() adminList = [] for admin in adminListRaw: a = Admin() a.email = admin[0] a.name = admin[1] adminList.append(a) return adminList
def register(): ''' 函数功能:接收注册信息,并检验注册验证码 函数返回:return jsonify({'code': {flag} }) flag为1则注册完成,为2则验证码错误或超时,为3则邮箱未申请验证码 ''' email = request.form.get('email') # string password = request.form.get('password') # string,密码是否一致在前端进行验证 newAdmin = Admin(email=email) newAdmin.hashPassword(password=password) newAdmin.createTime = datetime.now() db.session.add(newAdmin) db.session.commit() # 添加新用户 return jsonify({'code': 1}) # 注册完成
def index(): modelAdmin = Admin() if request.method =='POST': nama = request.form['nama'] password = request.form['password'] modelAdmin.setAdmin(nama,password) if modelAdmin.cek(): # print(nama + " "+ password) return render_template('Mainform.html') else: return render_template('login.html') return 'selamat ' + nama +' dan ' + password else: return render_template('login.html',modelAdmin=modelAdmin)
def change_password(): email = request.json.get('email', None) if not email or email == '': return None admin = Admin() admin.email = email admin = Admin.query.filter_by(email=email).first() if not admin: return jsonify({"msg": "This email is not registered"}), 404 token = generate_confirmation_token(admin.email) confirm_url = 'http://localhost:3000/confirmationadmin/' + token html = render_template('email_confirmation.html', confirm_url=confirm_url) subject = "Por favor, Confirmar su email." sendMail("Por favor, Confirmar su email.", admin.email, html) return jsonify({"success": "Email send successfully"}), 200
def entrada(pieza): forma = FormaEntrada() muestraObj = db.session.query(Muestra).filter_by(sku=pieza).first() if forma.validate_on_submit(): usuario = int(forma.empleado.data) admin = int(forma.encargado.data) usuarioObj = db.session.query(Usuario).filter_by( numero=usuario).first() if not usuarioObj: usuarioObj = Usuario(numero=usuario) adminObj = db.session.query(Admin).filter_by(numero=admin).first() if not adminObj: adminObj = Admin(numero=admin) muestraObj.cantidad = 1 ordenEntrega = Orden(muestra=muestraObj, usuario=usuarioObj, admin=adminObj, tipo='Entrada', timestamp=datetime.now()) db.session.add(ordenEntrega) db.session.commit() flash('Se entrego la pieza: {}'.format(muestraObj.sku)) return redirect(url_for('main')) return render_template('entrada.html', entrada=forma, pieza=muestraObj)
def otherUserRegistration(): if(session['logged_in'] == True): #if user login if(request.method == 'GET'): return render_template('OtherUsersRegistrationPage.html') elif(request.method == 'POST'): try: userId = request.json['user_id'] name = request.json['name'] userNIC = request.json['userNIC'] userType = request.json['userType'] newUser = "" if(userType == "teacher"): #if a teache, create new teacher object newUser = Teacher(userId, name, userNIC) if(userType == "admin"): #if a admin create new admin object newUser = Admin(userId, name, userNIC) DataPipelineObj.insert_data(newUser) #Add details to the database return jsonify({'status':"User successfully registered"}) except: return jsonify({'status':"Fill the required details"}) else: abort(405) else: #if user not login return render_template('showSignIn.html')
def get(self): if users.get_current_user(): #url = users.create_logout_url(self.request.uri) emailAddress = users.get_current_user().email() admins_Query = Admin.query(ancestor=PARENT_KEY).fetch() alreadyAdmin = False for admin in admins_Query: if admin.email.encode('ascii','ignore') == emailAddress: alreadyAdmin = True if (alreadyAdmin): # if an approved user is logged in: games_query = Game.query(ancestor=PARENT_KEY).fetch() users_query = User.query(ancestor=PARENT_KEY).fetch() logoutURL = users.create_logout_url(self.request.uri) template = jinja_env.get_template("templates/superSecretAdminPage.html") self.response.out.write(template.render({"logoutURL":logoutURL, "emailAddress":emailAddress, "games":games_query, "users":users_query, "admins":admins_Query})) else: # they are not an approved admin logoutURL = users.create_logout_url(self.request.uri) template = jinja_env.get_template("templates/adminSignInPage.html") self.response.out.write(template.render({"loginURL":logoutURL, "buttonText":"Logout"})) else: # there isn't anyone logged in loginURL = users.create_login_url(self.request.uri) template = jinja_env.get_template("templates/adminSignInPage.html") self.response.out.write(template.render({"loginURL":loginURL,"buttonText":"Login"}))
def addAdmin(): if request.method == 'POST': if 'admin' in session: # Request form data adminName = request.form['Name'] adminPassword = request.form['Password'] # Query database for data found_admin = Admin.query.filter_by(admin_name=adminName).first() if found_admin != '': flash('Admin already exists') return redirect(url_for('adminController.addAdmin')) else: # Add data to database admin = Admin(admin_name=adminName, admin_password=adminPassword) db.session.add(admin) db.session.commit() flash('New admin created successfully') return redirect(url_for('adminController.admin')) else: flash('Please Login') return redirect(url_for('adminController.adminLogin')) else: if 'admin' in session: return render_template('add-admin.jinja') else: abort(403)
def register(): form = RegistrationForm(request.form) if request.method == "POST": error = not form.validate_on_submit() else: error = False if request.method == 'GET' or error: return render_template("registration.html", form=form, error=error) elif request.method == 'POST': email = form.email.data name = form.name.data password = form.password.data if Admin.query.first(): role = 'normal' enabled = False else: role = 'full' enabled = True admin = Admin(name, email, password, enabled, role) token = utils.generate_confirmation_token(email) confirm_url = url_for('confirm', token=token, _external=True) html = render_template('confirmation_email.html', confirm_url=confirm_url, admin=admin) message = "Hi there {0}!\n\nThanks for signing up. Please follow this link to activate your account:\n\n{1}\n\nCheers!".format( admin.name, confirm_url) subject = "Please confirm your email" utils.mailgun_send_message(subject, [email], message, html=html) db.session.add(admin) db.session.commit() message = "Please check your inbox for a confirmation email." return render_template("success.html", message=message)
def test_check_password(self): """Check password.""" user = Admin.create(username='******', name='*****@*****.**', password='******') assert user.verify_password('foobarbaz123') is True assert user.verify_password('barfoobaz') is False
def POST(self): # username password remeber data = web.input(username="", password="", remeber="") try: result = Admin.getBy( username=data.username, password=hashlib.new("md5", data.password).hexdigest() ) if result == None: # 身份验证失败 # self.page.errinfo = "您输入的用户名和密码不匹配,请检查后重试." # print self.page.errinfo # return render.admin.login(page = self.page) return json.dumps({'err': '您输入的用户名和密码不匹配,请检查后重试'}) else: self.session.username = result.username self.session.nickname = result.nickname self.session.role = "admin" self.session.logged = True if data.remeber: # 记住密码 web.config.session_parameters['ignore_expiry'] = True return json.dumps({'success': '登录成功!'}) except Exception as err: self.page.title = "出错啦!" self.page.errinfo = err return render.errinfo(page=self.page)
def create_admin(): admin = Admin(username='******',password='******') try: db.session.add(admin) db.session.commit() except: db.session.rollback()
def decorated(*args, **kwargs): r = list(Admin.query(Admin.name=='admin')) if len(r) == 0 or (r[0].enabled == True and r[0].token == request.args.get('token', None)): # len(r) == 0: init admin return func(*args, **kwargs) else: return "404"
def admin(): if request.method == "GET": return base_req( response=[asdict(admin) for admin in Admin.query.all()]) if request.method == "POST": if "email" not in request.json: abort(400, "Missing key email") admin = Admin(email=request.json["email"]) db.session.add(admin) db.session.commit() return base_req() if request.method == "DELETE": if "email" not in request.json: abort(400, "Missing key email") search = Admin.query.filter_by(email=request.json["email"]).all() if not search: abort(404, "Admin with specified email does not exist") db.session.delete( Admin.query.filter_by(email=request.json["email"]).one()) db.session.commit() return base_req()
def main(): if Admin.login() is True: show() dic = { 0: show, 1: create_school, 2: show_school, 3: create_course, 4: show_course, 5: create_classes, 6: show_classes, 7: create_teacher, 8: show_teacher, 9: create_student, 10: show_student, 11: create_course_teacher, 12: show_course_teacher, 13: quit } flag = True while flag is True: choose = input('输入选项 >> ').strip() if choose.isdigit(): choose = int(choose) if choose <= len(dic): dic[choose]() elif choose == 'q': flag = False else: print('\033[31;0m用户名或密码不正确\033[0m')
def identify(self, request): """ 用户鉴权 :return: list """ auth_header = request.headers.get('Authorization') if (auth_header): auth_tokenArr = auth_header.split(" ") if (not auth_tokenArr or auth_tokenArr[0] != 'JWT' or len(auth_tokenArr) != 2): result = config.falseReturn('', '请传递正确的验证头信息') else: auth_token = auth_tokenArr[1] payload = self.decode_auth_token(auth_token) if not isinstance(payload, str): admin = Admin.get(Admin, payload['data']['id']) if (admin is None): result = config.falseReturn('', '找不到该用户信息') else: if (admin.update_time == payload['data']['login_time']): result = config.trueReturn(admin.id, '请求成功') else: result = config.falseReturn('', 'Token已更改,请重新登录获取') else: result = config.falseReturn('', payload) else: result = config.falseReturn('', '没有提供认证token') return result
def set_roles( user_id, is_recruiter=None, is_senior_recruiter=None, is_admin=None, current_user=None): user_admin_access_check(current_user) user = User.get(user_id) if is_senior_recruiter: if not user.recruiter: db.session.add(Recruiter(id=user.id, is_senior=True)) elif not user.recruiter.is_senior: user.recruiter.is_senior = True elif is_recruiter: if not user.recruiter: db.session.add(Recruiter(id=user.id, is_senior=False)) elif is_recruiter == False and user.recruiter: remove_recruiter(user.recruiter) if is_senior_recruiter == False and user.recruiter and user.recruiter.is_senior: user.recruiter.is_senior = False if is_admin and not user.admin: db.session.add(Admin(id=user.id)) elif is_admin == False and user.admin: db.session.delete(user.admin) db.session.commit() if is_recruiter or is_senior_recruiter or is_admin: delete_any_open_application(user_id) return {'status': 'ok'}
def create_admin(): data = request.get_json() if not data: return {"response": "No input data provided"}, 400 try: result = AdminSchema().load(data) except Exception: return jsonify({'response': "Invalid input"}), 400 if db.session.query(Admin.adminId).filter_by( username=result["username"]).scalar() is not None: return jsonify({'response': "Username is already used"}), 409 password = result["password"] salt = os.urandom(32) # Новая соль для данного пользователя key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 10000) storage = salt + key admin = Admin(username=result["username"], email=result["email"], password=storage) db.session.add(admin) db.session.commit() adminId = db.session.query( Admin.adminId).filter_by(username=result["username"]).scalar() encoded_jwt = bu.encode_auth_token(adminId, 1) return jsonify({ 'response': "Sign up successfully! Please LOG IN to get access token" }), 201
def post(self): admins_to_delete = json.loads(self.request.body) if not admins_to_delete: self.redirect('/admins') return admins = [Admin.get_by_key_name(name) for name in admins_to_delete] db.delete(admins)
def post(self): name = self.request.get('name') password = self.request.get('password') confirm = self.request.get('password-confirm') display = self.request.get('display') if name and password and confirm: other = Admin.all().filter('name = ', name).get() if not other and password == confirm: a = Admin.register(name, password, display=display) a.put() self.render_admins(msg="Successfully added new admin: %s" % name, type="success") return self.render_admins(msg="You must fill in a unique username, password, and confirmation", type="danger") return
def login(): if g.user is not None: return redirect('/') form = LoginForm() if form.validate_on_submit(): email = form.email.data.lower() password = md5.new(form.password.data).hexdigest() session['admin_id'] = Admin.query.filter_by(email=email, password=password).first() if session['admin_id']: session['admin_id'] = session['admin_id'].id session['next_url'] = '/index' return redirect(session['next_url']) try: l = ldap.initialize(Server) l.simple_bind_s(email, form.password.data) l.set_option(ldap.OPT_REFERRALS, 0) r = l.search(base, Scope, Filter.format(email), ["displayName"]) Type, user = l.result(r, 60) Name, Attrs = user[0] if 'displayName' in Attrs: displayName = Attrs['displayName'][0] admin = Admin.query.filter_by(email=email).first() if not admin: admin = Admin() admin.email = form.email.data admin.name = admin.email.split('.')[0].capitalize() admin.surname = admin.email.split( '.')[1].capitalize().split('@')[0] admin.password = password db.session.add(admin) db.session.commit() session['admin_id'] = admin.id return redirect(url_for('index')) except ldap.INVALID_CREDENTIALS: flash('Login or password error') except ldap.LDAPError, e: flash('LDAP-server error', e)
def login_auth(): admin = Admin() admin.user_name = request.form['username'] admin.password = request.form['password'] try: callback = request.form['callback'] except Exception as e: print(e) callback = None if admin.auth_admin(): if callback: # response = make_response(redirect(url_for('home'))) # response.set_cookie('session', SK_hash, 500) return admin.create_session('admin_session', callback, SK_hash, 500) else: return redirect(url_for('home')) flash('Username or password incorrect.') return redirect(url_for('login'))
def post(self): username = self.request.get('username') password = self.request.get('password') a = Admin.login(username, password) if a: self.login(a) self.redirect('/dashboard') else: msg = "Invalid credentials." self.render('admin/login', error=msg)
def create_admin_process(): admin = Admin() admin.name = request.form['name'] admin.phone = request.form['phone'] admin.user_name = request.form['username'] admin.password = request.form['password'] admin.address = { 'street': request.form['street'], 'city': request.form['city'], 'state': request.form['state'], 'zipcode': request.form['zipcode'], } admin.email = request.form['email'] admin.join_date = datetime.now() if admin.create_admin(): return redirect(url_for('create_admin', flash='Administrator created successfully.')) else: raise Exception
def POST(self): data = web.input(req='') req = data.req if req == "check": try: person = Admin.getBy( username=self.session.username, password=hashlib.new("md5", data.oldp).hexdigest() ) web.header('Content-Type', 'application/json') if person: return json.dumps({'is_valid': '1'}) else: return json.dumps({'is_valid': '0'}) except Exception as err: web.header('Content-Type', 'application/json') return json.dumps({'err': '出现错误: ' + str(err)}) elif req == "submit": try: person = Admin.getBy( username=self.session.username, password=hashlib.new("md5", data.oldp).hexdigest() ) web.header('Content-Type', 'application/json') if person is None: # 旧密码输错 return json.dumps({'err': '旧密码输入错误!'}) else: # 更新密码 person.password = hashlib.new("md5", data.newp).hexdigest() person.update() return json.dumps({'success': '密码修改成功'}) except Exception as err: web.header('Content-Type', 'application/json') return json.dumps({'err': '出现错误: ' + str(err)}) else: return web.Forbidden()
def POST(self): data = web.input(req='', username='', id='', newp='') req = data.req if req == 'check': try: person = Admin.getBy(username=data.username) web.header('Content-Type', 'application/json') if person == None: return json.dumps({'is_valid': '1'}) else: return json.dumps({'is_valid': '0'}) except Exception as err: web.header('Content-Type', 'application/json') raise err return json.dumps({'err': '出现错误: ' + str(err)}) elif req == 'submit': try: person = Admin.getBy(username=data.username) web.header('Content-Type', 'application/json') if person: # 用户名已被占用 return json.dumps({'err': '用户名已被占用!'}) else: # 更新密码 Admin(dict( username=data.username, password=hashlib.new('md5', data.newp).hexdigest(), role=data.role, )).insert() return json.dumps({'success': '成功添加用户'}) except Exception as err: web.header('Content-Type', 'application/json') return json.dumps({'err': '出现错误: ' + str(err)}) elif req == 'delete': if not data.id: return json.dumps({'err': '请求出错'}) person = Admin.get(data.id) operator = Admin.getBy(username=self.session.username) if not person: return json.dumps({'err': '用户不存在'}) if operator.role >= person.role: return json.dumps({'err': '无权限'}) person.delete() return json.dumps({'success': '已删除'}) elif req == 'update': person = Admin.getBy(username=data.username) operator = Admin.getBy(username=self.session.username) if not person: return json.dumps({'err': '用户不存在'}) if operator.role >= person.role: return json.dumps({'err': '无权限'}) person.password = hashlib.new('md5', data.newp).hexdigest() person.update() return json.dumps({'success': '修改成功!'}) else: return web.Forbidden()
def ajax_admin_list(request): #需要登录才可以访问 if not request.session.get("sess_admin", False): return commons.res_fail(1, "需要登录才可以访问") #分页索引和每页显示数 page = 1 if request.GET.get("page"): page = int(request.GET.get("page")) page_size = cfg.page_size if request.GET.get("page_size"): page_size = int(request.GET.get("page_size")) res_data = Admin.getList(page, page_size) return commons.res_success("请求成功", res_data)
def init_admin(): c = g.template_context g.admin = c['user'] = Admin.get_current() # login required for all admin pages / API requests if not g.admin and request.path != '/admin/login': return redirect('/admin/login') g.page_id = request.path.replace('/admin', '').strip('/') """ By default we use the same template for simple page and admin version of that page. We change layout (header, content wrapper, footer) using layout var """ c.update(dict( admin = True, admin_title = 'Starter', layout = 'admin/layout.html', page_id = g.page_id ))
def get(self): """The API to get comfort records from the database. Allows for the following parameters: key - (required) the admin's API key location - (optional) the location to get data from level - (optional) the level of comfort (can be specified as a range) from - (optional) the time to go from to - (optional) the time to go to The response is returned as a JSON object with the data requested, or an error with a description. """ key = self.request.get('key') a = Admin.by_api_key(key) if not a: self.render_json(errors.INVALID_KEY) return location = self.request.get('location') comforts = self.comforts_by_location(location) level = self.request.get('level') level_filter = self.create_level_filter(level) if level_filter: comforts = filter(level_filter, comforts) frm = self.request.get('from') frm_filter = self.create_date_filter(frm, FROM) if frm_filter: comforts = filter(frm_filter, comforts) to = self.request.get('to') to_filter = self.create_date_filter(to, TO) if to_filter: comforts = filter(to_filter, comforts) if self.error_code: self.render_json(self.error_code) else: self.render_json([comfort.as_dict() for comfort in comforts][:MAX_RECORDS]) a.record_api_access()
def login(): user = Admin.find_one({ 'email': request.forms.email }) password = request.forms.get('password', None) if password is None: # forgot password if user: result = { 'success': 'EmailSent' } else: result = { 'error': 'EmailError' } elif user and user.verify_password(password): # checkbox "Remember Me" temporary_login = '******' not in request.forms user.set_as_current(temporary=temporary_login) result = { 'error': False, 'redirect': users_app.config['home'] } else: result = { 'error': 'LoginError' } return result
def admin_init(): import random admin = Admin(id="0", enabled=True, name='admin', token=hashlib.md5(str(random.random()).encode('utf-8')).hexdigest()[:16]) admin.put() return 'OK'
def initialize(self, *a, **kw): webapp2.RequestHandler.initialize(self, *a, **kw) aid = self.read_secure_cookie('admin_id') self.admin = aid and Admin.by_name(aid) self.json = self.request.url.endswith('.json')
return (raw_input('Username:'******'Password:'******'/_ah/remote_api', auth_func, 'localhost') from models import Admin, Location, Comfort #if len(list(Admin.all())) == 0: # add initial user, we do not backup the admin tabl a = Admin.register('admin', 'default', display='admin') a.put() print 'ADMINS:' for a in Admin.all(): print a.display, a.name, a.passhash, a.created import json def from_utc(utcTime,fmt="%Y-%m-%dT%H:%M:%S"): """ Convert UTC time string to time.struct_time """ # change datetime.datetime to time, return time.struct_time type return datetime.datetime.strptime(utcTime, fmt)
def get_admin(self): aid = self.read_secure_cookie('admin_id') if aid: return Admin.by_name(aid)
def create_admin(): admin = Admin() if admin.check_if_admin_exist(): if not Security.is_login(SK): return redirect(url_for('login', callback='create_admin')) return render_template('settings/create_admin.html', title="Create Administrator")
def render_admins(self, **kwargs): admin = self.get_admin() admins = list(Admin.all()) self.render('admin/accounts', admin=admin, admins=admins, **kwargs)
import traceback from settings import active_config, live_config app = create_app(schedule_events=False) app.app_context().push() client = app.test_client() config = active_config() if __name__ == '__main__': customer = sys.argv[1] if len(sys.argv) > 1 else 'weppa' print '-'*20, '\nCUSTOMER: {}\n'.format(customer), '-'*20 switch_customer(customer) or exit() print '>> creating admin account....' try: admin = Admin.objects(email='*****@*****.**').first() if not admin: admin = Admin() admin.enabled = True admin.first_name = 'Luke' admin.last_name = 'Zhao' admin.last_name_norm = 'Zhao' admin.locale = 'en-us' admin.password = Account.generate_password('AdmiN') admin.email = '*****@*****.**' admin.role = 'system' admin.save() else: admin.password = Account.generate_password('AdmiN') admin.save() admin = Admin.objects(email='*****@*****.**').first()