def profile(): if request.method == "POST": try: if not session.__contains__('user_id'): return jsonify({'success': False}) old_user_id = int(request.form.get('old_user_id')) new_user_id = int(request.form.get('new_user_id')) permission = int(request.form.get('permission')) first_name = request.form.get('first_name') last_name = request.form.get('last_name') db = db_init() stored_user = db.execute("SELECT * FROM users WHERE id IS :id", { 'id': old_user_id }).fetchone() if not stored_user['permission'] < session[ 'user_permission'] or permission >= session[ 'user_permission']: raise Exception('Permission Error') db.execute( "UPDATE users SET first_name = :first_name, last_name = :last_name, id = :new_user_id, " "permission = :permission WHERE id = :old_user_id", { 'first_name': first_name, 'last_name': last_name, 'new_user_id': new_user_id, 'old_user_id': old_user_id, 'permission': permission }) db.commit() return jsonify({ 'success': True, 'name': first_name + " " + last_name, 'position': get_user_position(permission) }) except: return jsonify({'success': False}) else: if not session.__contains__('user_id'): return redirect(url_for('index')) if not request.args.__contains__("id"): user_id = session['user_id'] else: user_id = request.args.get('id') db = db_init() stored_user = db.execute("SELECT * FROM users WHERE id IS :id", { 'id': user_id }).fetchone() if stored_user is None: stored_user = db.execute("SELECT * FROM users WHERE id IS :id", { 'id': session['user_id'] }).fetchone() stored_user['position'] = get_user_position(stored_user['permission']) disabled = ('disabled', '')[session['user_permission'] > stored_user['permission']] return render_template("user.html", user=stored_user, disabled=disabled)
def load_user(): if session.__contains__('user_name'): user = session["user_name"] else: user = None if session.__contains__('user_name'): session.pop('user_name', None) if session.__contains__('user_group'): session.pop('user_group', None) if session.__contains__('is_admin'): session.pop('is_admin', None) g.user = user
def login_parent(): if session.__contains__('logged_in') and session['logged_in'] is True: flash("You are already logged in") return redirect(url_for('index')) # Output message if something goes wrong... msg = '' # Check if "username" and "password" POST requests exist (user submitted form) if request.method == 'POST' and 'email' in request.form and 'password' in request.form: # Create variables for easy access email = request.form['email'] password = request.form['password'] # Check if account exists using MySQL cursor = mysql.connection.cursor() cursor.execute( 'SELECT * FROM PARENT WHERE EMAIL = %s AND P_PASSWORD = %s', (email, password)) # Fetch one record and return result account = cursor.fetchone() cursor.close() # If account exists in accounts table in out database if account: # Create session data, we can access this data in other routes session['logged_in'] = True print(session['logged_in']) session['logged_in_as'] = 'Parent' session['parent_student_usn'] = account[5] # Redirect to home page return redirect('/') else: # Account doesnt exist or username/password incorrect msg = 'Incorrect username/password!' # Show the login form with message (if any) return render_template('login_parent.html', msg=msg)
def registration_parent(): if session.__contains__('logged_in') and session['logged_in'] is True: flash("Action not allowed") return redirect(url_for('index')) cursor = mysql.connection.cursor() if request.method == 'POST': # Fetch form data parent_details = request.form name = parent_details['name'] phone_number = parent_details['contact'] email = parent_details['email'] password = parent_details['password'] student = parent_details['selected-student'] if student == '0': flash("Invalid details provided") return redirect('/registration-parent') cursor.execute( "INSERT INTO PARENT(P_NAME, PHONE, EMAIL, P_PASSWORD, S_PICKED_USN) VALUES(%s, %s, %s, %s, %s)", (name, phone_number, email, password, student)) mysql.connection.commit() cursor.execute('UPDATE STUDENT SET REGISTERED = TRUE WHERE USN = %s', (student, )) mysql.connection.commit() cursor.close() return redirect('/') cursor.execute('SELECT USN, NAME FROM STUDENT WHERE REGISTERED = FALSE') students = cursor.fetchall() print(students) return render_template('registration_parent.html', students=students)
def logout(): """ sets logout """ if session.__contains__('username'): session.pop('username') return redirect('/') return redirect('login')
def dashboard(): if not session.__contains__('user_id'): return redirect(url_for('index')) return render_template('dashboard.html', user=db_init().execute( "SELECT * FROM users WHERE id IS :id", { 'id': session['user_id'] }).fetchone())
def buy(): product_id = request.form.get("product_id") add = int(request.form.get("add")) if add is 0: if session.__contains__('cart') and product_id in session['cart']: cart = dict(session['cart']) cart.pop(product_id, None) session['cart'] = cart return jsonify({'success': True}) product_data = num_products[int(product_id)] product_data['quantity'] = add if session.__contains__('cart'): cart = dict(session['cart']) if cart.__len__() >= MAX_ITEMS_IN_CART and add > 0: return apology('Слишком много вещей в корзине' ) # TODO: notify instead of apology if cart.__contains__(product_id): result = cart[product_id]['quantity'] + add if result > MAX_ITEMS_IN_CART or result < 0: return apology('Неправильное количество') if result is not 0: cart[product_id]['quantity'] = result else: del cart[product_id] else: if add > 0: cart[product_id] = product_data else: return apology('Нечего удалять') elif add > 0: cart = {product_id: product_data} else: return apology('Invalid quality') session['total_cart'] = get_total(cart) session['cart'] = cart if session.__contains__('user_id'): db = db_init() save_cart(db, session['user_id'], session['cart']) return jsonify({ 'success': True, 'new_mini_cart': render_template('mini_cart.html'), 'notify': "Item added successfully" })
def index(): print "user_name: " + str(session.get('user_name')) print "is_admin: " + str(session.get('is_admin')) if session.__contains__('user_group'): return jsonify([session['user_name'], session['user_group']]) if g.user is None: user = User(name="guest", role='anonymous') return jsonify([user.name, user.role]) else: return jsonify(g.user)
def get(self, uid, pwd): if session.__contains__(USER_SESSION): User.add(session[USER_SESSION]) return self.fail("已登录") if not session.__contains__(KEY_SESSION): raise ExceptionEx("未申请密钥") uid = crypt.desc(uid) pwd = crypt.desc(pwd) ldap = Ldap() if not ldap.auth(uid, pwd): return self.fail("用户名或密码错误") dn, _user = ldap.search(uid).first() User.add(_user) session[USER_SESSION] = _user return self.succ(session[USER_SESSION])
def index(): "主页" if(session.__contains__("uid")): #已登录用户直接进入后台 return redirect("/admin") if(request.args.get("error",None)==None): error=False else: error=True return render_template("index.html",error=error)
def send(photolog_id): """ photolog_id에 해당하는 사진과 커멘트를 트위터로 전송하는 뷰함수 """ if (session.__contains__('TWITTER')): twitter = session['TWITTER'] __send_twit(twitter, photolog_id) return redirect(url_for('.show_all')) else: # twitter 객체가 세션에 없을경우 인증단계로 이동한다. return __oauth(photolog_id)
def send(Rate_id): """ Rate_id에 해당하는 사진과 커멘트를 트위터로 전송하는 뷰함수 """ """""" if (session.__contains__('TWITTER')): twitter = session['TWITTER'] __send_twit(twitter, Rate_id) return redirect(url_for('.show_all')) else: # twitter 객체가 세션에 없을경우 인증단계로 이동한다. return __oauth(Rate_id)
def decorated_function(*args, **kwargs): try: session_key = \ request.cookies.get( current_app.config['SESSION_COOKIE_NAME']) if not (session.sid == session_key and session.__contains__(SessionResources().const.MEMBER_ID)): session.clear() return redirect(url_for(RouteResources().const.SIGN_IN)) return f(*args, **kwargs) except Exception: from GradeServer.utils.utilMessages import unknown_error return unknown_error ()
def decorated_function(*args, **kwargs): try: session_key = request.cookies.get( current_app.config['SESSION_COOKIE_NAME']) print('session_key:[%s]' % session_key) is_login = False if session.sid == session_key and session.__contains__('usn'): is_login = True if not is_login: return redirect(url_for('.login_form', next=request.url)) return f(*args, **kwargs) except Exception as e: Log.error('Login error : %s' % str(e))
def send(photolog_id): """ photolog_id에 해당하는 사진과 커멘트를 트위터로 전송하는 함수 """ if (session.__contains__('TWITTER')): twitter = session['TWITTER'] # 파라미터로 받은 photolog_id를 이용하여 해당 사진과 커멘트를 트위터로 전송한다. photo_info = get_photo_info(photolog_id) download_filepath = photo_info[2] photo_comment = photo_info[3] photo = open(download_filepath, 'rb') twitter.update_status_with_media(status=photo_comment, media=photo) return redirect(url_for('.show_all')) else: # twitter 객체가 세션에 없을경우 인증단계로 이동한다. return redirect(url_for('.oauth', photolog_id=photolog_id))
def registration_teacher(): if session.__contains__('logged_in') and session['logged_in'] is True: flash("Action not allowed") return redirect(url_for('index')) if request.method == 'POST': # Fetch form data teacher_details = request.form name = teacher_details['name'] email = teacher_details['email'] password = teacher_details['password'] cur = mysql.connection.cursor() cur.execute( "INSERT INTO TEACHER(TEACHER_NAME, T_EMAIL, T_PASSWORD) VALUES(%s, %s, %s)", (name, email, password)) mysql.connection.commit() cur.close() return redirect('/') return render_template('registration_teacher.html')
def decorated_function(*args, **kwargs): try: session_key = request.cookies.get( current_app.config['SESSION_COOKIE_NAME']) is_login = False if session.sid == session_key and session.__contains__( 'user_info'): is_login = True if not is_login: return redirect(url_for('.login_form', next=request.url)) return f(*args, **kwargs) except Exception as e: Log.error("Phtolog error occurs: %s" % str(e)) raise e
def decorated_function(*args, **kwargs): """Check whether logged in""" try: session_key = request.cookies.get( current_app.config['SESSION_COOKIE_NAME']) is_login = False if session.sid == session_key and session.__contains__( 'user_info'): is_login = True if not is_login: return redirect(url_for('web_frame.login', next=request.url)) return f(*args, **kwargs) except Exception as e: Log.error('Web error: %s' % str(e)) raise e
def decorated_function(*args, **kwargs): try: session_key = \ request.cookies.get(current_app.config['SESSION_COOKIE_NAME']) is_login = False if session.sid == session_key and \ session.__contains__('user_info') : is_login = True if not is_login: return redirect(url_for('.login_form', next=request.url)) return f(*args, **kwargs) except Exception as e: Log.error("while checking session, error occurs : %s" % str(e)) raise e
def deco_func(*args, **kwargs): try: session_key = request.cookies.get(app.config['SESSION_COOKIE_NAME']) is_login = False print str(session.sid) + " == " + str(session_key) + " : " + str(session.sid == session_key) print 'session.__contains__("userid") : ' + str(session.copy()) if session.sid == session_key and session.__contains__('userid'): is_login = True if not is_login: print '로그인 필요' flash("login please.") return redirect('/') return f(*args, **kwargs) except Exception as e: print '에러 : ' + str(e) raise e
def decorated_function(*args, **kwargs): try: session_key = \ request.cookies.get( current_app.config['SESSION_COOKIE_NAME']) is_login = False if session.sid == session_key and \ session.__contains__('user_info') : is_login = True if not is_login: return redirect('login') return f(*args, **kwargs) except Exception as e: Log.error("SmartClinicServ error occurs : %s" % str(e)) raise e
def log(app, changes): try: uri = app.config["SQLALCHEMY_DATABASE_URI"] user, passwd, host, _db = re.compile("mysql://(.+):(.+)@(.+):[0-9]+/(.+)").findall(uri)[0] if session.__contains__(USER_SESSION): with MySQLdb.connect(user=user, passwd=passwd, host=host, db=_db, charset="utf8") as cursor: for obj, action in changes: cursor.execute( "insert into log_sqlalchemy " "(`action`,`table`,`object`,`uid`,`create_time`) VALUES (%s,%s,%s,%s,%s)", (action, obj.__class__.__name__, obj._to_dict(obj).__str__(), session[USER_SESSION]["uid"], datetime.now()) ) except Exception, e: app.logger.exception(e) traceback.print_exc()
def put(self, uid, oldpass=None, newpass=None): if not oldpass: if not session.__contains__(USER_SESSION): raise ExceptionEx("未登录") if not User.get(session[USER_SESSION]["uid"])["is_admin"]: raise ExceptionEx("权限不足") if not uid or uid in ["*", u"*"]: return self.fail("无效的用户名") newpass = newpass if newpass else crypt.randpass() ldap = Ldap() if not ldap.reset_pwd(uid, newpass, oldpass): return self.fail() mail = Mail() mail.to(uid, newpass) return self.succ() if oldpass else self.succ(newpass)
def decorated_function(*args, **kwargs): try: session_key = \ request.cookies.get( current_app.config['SESSION_COOKIE_NAME']) if not (session.sid == session_key and session.__contains__( SessionResources().const.MEMBER_ID)): session.clear() return redirect( url_for(RouteResources().const.SIGN_IN_NEWPAGE, to=f.__name__, params=kwargs)) return f(*args, **kwargs) except Exception: from GradeServer.utils.utilMessages import unknown_error return unknown_error()
def log(app, changes): try: uri = app.config["SQLALCHEMY_DATABASE_URI"] user, passwd, host, _db = re.compile( "mysql://(.+):(.+)@(.+):[0-9]+/(.+)").findall(uri)[0] if session.__contains__(USER_SESSION): with MySQLdb.connect(user=user, passwd=passwd, host=host, db=_db, charset="utf8") as cursor: for obj, action in changes: cursor.execute( "insert into log_sqlalchemy " "(`action`,`table`,`object`,`uid`,`create_time`) VALUES (%s,%s,%s,%s,%s)", (action, obj.__class__.__name__, obj._to_dict(obj).__str__(), session[USER_SESSION]["uid"], datetime.now())) except Exception, e: app.logger.exception(e) traceback.print_exc()
def index(): if session.__contains__('initialize') == False: session['userSentence'] = None session['tweetThread'] = None session['metamodelThread'] = None session['languageProcessingThread'] = None session['completeTweetFetch'] = False session['completedMetaModel'] = False session['realtime'] = True session['initialize'] = True form = SearchForm() if form.validate_on_submit(): flash("User input = '" + form.user_input_string.data +"' will be analyzed ") print form.user_input_string.data session['usersentence'] = form.user_input_string.data.__str__() session['realtime'] = bool(form.realtime.data.__str__()) myapp = current_app._get_current_object() session['languageProcessingThread'] = thread.start_new_thread(DataDownloaderMethods.twitterdownloadInitiator,(myapp, session['usersentence'], session['realtime'],)) return redirect(url_for('.analyze')) return render_template('index.html', title='Home', form=form)
def change_password(): if not session.__contains__('user_id'): return jsonify({'success': False}) try: old_password = request.form.get('old_pass') new_password = request.form.get('new_pass') db = db_init() stored_user = db.execute("SELECT * FROM users WHERE id IS :id", { 'id': session['user_id'] }).fetchone() if stored_user['password'] != old_password: raise Exception('Wrong Password') if len(new_password) < 6: raise Exception('Too Short Password') db.execute( "UPDATE users SET password = :new_password WHERE id = :user_id", { 'new_password': new_password, 'user_id': session['user_id'] }) db.commit() return jsonify({'success': True}) except: return jsonify({'success': False})
def cart(): if request.method == "POST": first_name = request.form.get("first-name") last_name = request.form.get("last-name") city = request.form.get("city") delivery = request.form.get("delivery") phone = request.form.get("phone") email = request.form.get("email") password = request.form.get("password") additional = request.form.get( "additional") # TODO additional information changes = ast.literal_eval(request.form.get("changes")) for id in changes: session['cart'][id]['quantity'] += changes[id] session['total_cart'] = get_total(session['cart']) try: v = email_validator.validate_email(email, check_deliverability=False) email = v["email"] except email_validator.EmailNotValidError as e: return apology("Некорректный email: " + str(e)) if len(first_name) < 1 or len(last_name) < 1 or len(city) < 1 or len( delivery) < 1: return apology("Некорректные данные") if len(phone) < 8: return apology('Некорректный номер телефона') db = db_init() user = db.execute("SELECT * FROM users WHERE username = :username", { "username": email }).fetchall() if len( user ) == 1: # TODO: debug save user + make based on id instead of username db.execute( "UPDATE users SET firstname = :firstname, lastname = :lastname, " "phone = :phone, delivery = :delivery WHERE username = :username", { "firstname": first_name, "lastname": last_name, "phone": phone, "delivery": delivery, "username": email }) else: if password is not None: # TODO: check if db doesn't contain user already db.execute( "INSERT INTO users (username, password, firstname, lastname, phone, delivery) " "VALUES(:username, :hash, :firstname, :lastname, :phone, :delivery)", { "username": email, "hash": pwd_context.hash(password), "firstname": first_name, "lastname": last_name, "phone": phone, "delivery": delivery }) date = str(datetime.now()) db.execute( "INSERT INTO orders " "(email, phone, city, delivery, cart, total_sum, date, additional_information) " "VALUES (:email, :phone, :city, :delivery, :cart, :total, :date, :additional)", { 'email': email, 'phone': phone, 'city': city, 'delivery': delivery, 'cart': get_short_cart(session['cart']), 'total': session['total_cart'], 'date': date, 'additional': additional }) order = db.execute("SELECT id FROM orders WHERE date IS :date", { 'date': date }).fetchone() db.commit() session['cart'].clear() save_cart(db, session['user_id'], session['cart']) return url_for('success', id=order['id']) else: if is_cart_empty(): col_md = 9 else: col_md = 15 if session.__contains__('user_id'): db = db_init() user = get_user_for_checkout(db) return render_template('checkout.html', email=user['username'], firstname=user['firstname'], col_md=col_md, lastname=user['lastname'], city=user['city'], delivery=user['delivery']) return render_template('checkout.html', col_md=col_md)
def deal(*args, **kwargs): if(not session.__contains__("uid")): return redirect("/") return fn(*args, **kwargs)
def is_cart_empty(): return not session.__contains__("cart") or session['cart'].__len__() == 0
def auth(self): session.permanent = True if session.__contains__(USER_SESSION): return True return False
def before_request(): if (session.__contains__('username')): g.user = User.query.filter_by (username=session['username']).first()
def register(): if session.__contains__('logged_in') and session['logged_in'] is True: flash("Action not allowed") return redirect(url_for('index')) return render_template('registration.html')
def login(): if session.__contains__('logged_in') and session['logged_in'] is True: flash("You are already logged in") return redirect(url_for('index')) return render_template('login.html')
def index(): # session['user_id'] = 1000000 # TODO: REMOVE # session['user_permission'] = 2 # TODO: REMOVE if not session.__contains__('user_id'): return redirect('/login') return redirect('/dashboard')
def decorated_function(*args, **kwargs): if not session.__contains__('username'): return redirect(url_for('login')) return func(*args, **kwargs)