def client_login(params): code = params.get("code") if not code or len(code) != 36: return {"error_code": 1, "msg": "params invalid"} key = "jump-%s" % code obj = misc.misc_get(key) if not obj: return {"error_code": 1, "msg": "code not exists"} dic = utils.loads(obj.value) obj.delete_instance() if dic['expire_at'] < utils.stamp(): return {"error_code": 1, "msg": "code expire"} user = User.select().where(User.id == dic['user_id']).first() res = {"error_code": 0, "msg": "ok"} res['session_token'] = generate_token() sess = Session() sess.user = user sess.session_key = res['session_token'] sess.expire_at = utils.timedelta(utils.now(), days=1) res['expire_at'] = 0 sess.save() res['identify'] = user.identify return res
def post(self): # Get POST data email = self.request.get("email") password = self.request.get("psw") # Check if user exists user = User.query(User.email == email).fetch() if not user: return self.write("Email or password is wrong") # Compare hashed password with value in database salt = "d9be95247" password = sha256(salt + password + salt).hexdigest() if password != user[0].password: return self.write("Email or password is wrong") # Create session token token = sha256(str(time.time()) + user[0].email).hexdigest() # Write new session in database new_session = Session(token=token, user_email=user[0].email) new_session.put() # Write token to cookie self.response.set_cookie("token", token) return self.redirect("/")
def login(): try: email = request.json['email'] password = request.json['password'] except KeyError as e: return jsonify({'error': 'Missing field(s).', 'details': str(e)}), 401 try: if email != 'admin': user = User.find_one(email=email) if not user or not user.check_password(password): raise ValueError() role = user.role else: role = 'admin' if password != config.ADMIN_PASSWORD: raise ValueError() s = Session(email=email, role=role) s.save() session['token'] = s.token session['email'] = email return Response(status=200) except ValueError: return Response(status=401)
def xpath_user_sessions(self, content): tree = html.fromstring(content) logging.debug("DOM created...") if 'Текущий сеанс' in tree.xpath( '//div[contains(@class,"list_item")]/div/b/text()'): logging.error("Session protection (admin?)") return [] sess_raw_list = tree.xpath( '//div[contains(@class,"list_item")]/div/span/following-sibling::text()[1]' ) sess_list = [] logging.debug("List items: " + str(len(sess_raw_list))) for i in range(0, len(sess_raw_list), 3): date = self.spac_date.get_python_time(sess_raw_list[i]) logging.debug("RawTime: " + str(date)) logging.debug("RawIP: " + sess_raw_list[i + 1]) ip_raw = self.text_ip_split(sess_raw_list[i + 1]) ip = ip_raw.ip ip_place = ip_raw.ip_place.strip() logging.debug("IP: " + ip + "; Place: " + ip_place) ua = sess_raw_list[i + 2].strip() logging.debug("UA" + ua) sess_list.append(Session(date, ua, "", ip, ip_place)) return sess_list
def retrieve(self, account_id=None, session_id=None): ''' retrieves the session id from cache ''' try: # see how to get session, either by session id or by account id if account_id: session_return = Session() session_return.account_id = account_id raw_session = self.redis_conn.get(self.session_key_format % account_id) if raw_session: timestamp, session_id = raw_session.split(':') session_return.session_id = session_id session_return.date_updated = datetime.fromtimestamp( int(timestamp)) return session_return elif session_id: session_return = Session() session_return.session_id = session_id raw_session = self.redis_conn.get( self.session_by_id_key_format % session_id) if raw_session: timestamp, account_id = raw_session.split(':') session_return.date_updated = datetime.fromtimestamp( int(timestamp)) session_return.account_id = account_id return session_return else: return None except Exception, e: raise SessionError( '%s : exception raised while trying to retrieve session: %s' % (self.name, e))
def generate_session(self, user_key: str, level: Level, difficulty_score: float) -> str: # Variable intended to store the key # that will be created within the function. session_id: int = 0 # Fetches the ids of all previously played sessions. session_ids: [int] = self.get_session_ids(user_key) # Checks whether at least a single session has been # stored before for a given user. if len(session_ids) > 0: # Sets the id for the session that should be # created next to one higher than previous # session id. session_id = max(session_ids) + 1 # Generates a key that corresponds to the previously # created id like 'session_042' if the session's id # is '42' session_key: str = Helper().generate_key('session', session_id) # Defines a new performance object which values are # initialized with zeros. performance: Performance = Performance(0, 0, 0, 0, 0, 0, 0, difficulty_score) # Creates a new session object based on the previously # defined key and id pair. session: Session = Session(session_key, session_id, 'created', server_timestamp, performance) # Defines a new database reference pointing towards # the place at which the new session sould be stored. ref = db.document(f'users/{user_key}/sessions/{session_key}') # Writes the generated session to Firestore. ref.set(session.to_dict()) # Defines a new database reference at which the session's # performance should be stored. ref = db.document( f'users/{user_key}/sessions/{session_key}/data/performance') # Stores the session's performance. ref.set(performance.to_dict()) # Defines a new database reference pointing to the place at # which the level for the generated session should be stored. ref = db.document( f'users/{user_key}/sessions/{session_key}/data/level') # Stores the session's level at Firestore. ref.set(level.to_dict()) # Returns the key of the generated session. return session_key
def signout(): if request.cookies.get('session'): ses = Session() ses.delete(request.cookies.get("session")) res = make_response(redirect("/authen/signin")) res.set_cookie("session", "", max_age=-1) return res return redirect("/authen/signin")
def select(id): session = None sql = "SELECT * FROM sessions WHERE id = %s" values = [id] result = run_sql(sql, values)[0] session = Session(result["name"], result["description"], result["upcoming"], result["capacity"], result['offpeak'], result["id"]) return session
def create_session(): name = request.form["name"] time = request.form["time"] date = request.form["date"] duration = request.form["duration"] capacity = request.form["capacity"] new_session = Session(name, time, date, duration, capacity) session_repo.save(new_session) return redirect("/sessions")
def update_session(id): name = request.form["name"] date = request.form["date"] time = request.form["time"] duration = request.form["duration"] capacity = request.form["capacity"] session = Session(name, date, time, duration, capacity, id) session_repository.update(session) return redirect("/sessions")
def show_past_sessions(): past_s = [] sql = "SELECT * FROM sessions WHERE sessions.upcoming = False" results = run_sql(sql) for row in results: past = Session(row['name'], row['description'], row['upcoming'], row['capacity'], row['offpeak'], row['id']) past_s.append(past) return past_s
def select(id): session = None sql = "SELECT * FROM sessions WHERE id = %s" values = [id] result = run_sql(sql, values)[0] if result is not None: session = Session(result["name"], result["date"], result["time"], result["duration"], result["capacity"], result["id"]) return session
def signout(): if request.cookies.get('session'): ses = Session() ret = ses.delete(request.cookies.get('session')) res = make_response(redirect('/authen/signin')) res.set_cookie('session', '', max_age= -1) return res return redirect('authen/signin')
def select_all_by_date(): sessions = [] sql = "SELECT * FROM sessions ORDER BY date, time ASC" results = run_sql(sql) for row in results: session = Session(row["name"], row["date"], row["time"], row["duration"], row["capacity"], row["id"]) sessions.append(session) return sessions
def select_all(): sessions = [] sql = "SELECT * FROM sessions" results = run_sql(sql) for result in results: session = Session(result["name"], result["time"], result["date"], result["duration"], result["capacity"], result["id"]) sessions.append(session) return sessions
def select(id): session = None sql = "SELECT * FROM sessions WHERE id = %s" values = [id] result = run_sql(sql, values)[0] if result is not None: session = Session(result['name'], result['category'], result['id']) return session
def select_all(): sessions = [] sql = "SELECT * FROM sessions" results = run_sql(sql) for row in results: session = Session(row['name'], row['description'], row['upcoming'], row['capacity'], row['offpeak'], row['id']) sessions.append(session) return sessions
def show_upcoming(): upcoming = [] sql = "SELECT * FROM sessions WHERE sessions.upcoming = True" results = run_sql(sql) for row in results: session = Session(row['name'], row['description'], row['upcoming'], row['capacity'], row['offpeak'], row['id']) upcoming.append(session) return upcoming
def get(self): session_id = request.cookies.get("session_id") Session().delete(session_id) res = self.json_response(status=1, data={}, msg="success") if session_id: res.set_cookie(key='session_id', value=session_id, max_age=0) return res
def select_all(): sessions = [] sql = "SELECT * FROM sessions" results = run_sql(sql) for row in results: session = Session(row['name'], row['category'], row['id']) sessions.append(session) return sessions
def select_classes_booked_for(id): sessions = [] sql = "SELECT sessions.* FROM sessions INNER JOIN bookings ON bookings.session_id = sessions.id WHERE bookings.member_id = %s" values = [id] results = run_sql(sql, values) for result in results: session = Session(result["name"], result["description"], result['upcoming'], result['capacity'], result['offpeak'], result['id']) sessions.append(session) return sessions
def sessions(member): sessions = [] sql = "SELECT sessions.* FROM sessions INNER JOIN bookings ON bookings.session_id = sessions.id WHERE member_id = %s" values = [member.id] results = run_sql(sql, values) for row in results: session = Session(row['name'], row['category'], row['id']) sessions.append(session) return sessions
def sessions(member): sessions = [] sql = "SELECT sessions.* FROM sessions INNER JOIN bookings ON bookings.session_id = sessions.id WHERE member_id = %s ORDER BY date, time ASC" values = [member.id] results = run_sql(sql, values) for row in results: session = Session(row["name"], row["date"], row["time"], row["duration"], row["capacity"], row["id"]) sessions.append(session) return sessions
def test_db_upsert(db): history = [ History(datetime.datetime(2016, 12, 31, 23, 59, 59), "mozillo1"), History(datetime.datetime(2015, 11, 30, 22, 58, 59), "mozillo2") ] session = [ Session(datetime.datetime(2016, 12, 31, 23, 59, 59), "mozillo1", "192.0.0.1", "msk") ] user = User(1, "test_user", history, session) db.upsert_user(user) return
def new_session(user, message, response): sms_session = Session(user_id=user.id, interval_id=user.interval.id) models.storage.new(sms_session) models.storage.save() if message.strip().lower() == user.predictor.name: sms_response = Response(session_id=sms_session.id, predictor_id=user.predictor.id, user_id=user.id, message=message, twilio_json="{}") models.storage.new(sms_response) models.storage.save() else: response.message('This should be the predictor.')
def doEditPassword(id): acc = Account() v = acc.getAccountById(id) usr = v['usr'] newpwd = request.form.get("pwd") + '#$%^&*$@' + usr newpwd = md5(newpwd.encode()) a = (newpwd.digest(), id) ret = acc.editPassword(a) if ret > 0: if request.cookies.get('session'): ses = Session() ses.delete(request.cookies.get("session")) res = make_response(redirect("/authen/signin")) res.set_cookie("session", "", max_age=-1) return res return "Failed"
def loginUser(): if 'Authorization' not in request.headers: return jsonify({'ACK': 'FAILED', 'message': 'Permission denied.'}) auth = request.headers['Authorization'] encoded_info = auth.replace('Basic ', '', 1) user = '' password = '' try: userpasswd = base64.b64decode(encoded_info).decode('utf-8') user = userpasswd.split(':')[0] password = userpasswd.split(':')[1] except: return jsonify({'ACK': 'FAILED', 'message': 'Wrong session.'}) result = db.session.query(Coordinator, User).join( User, User.pecfestId == Coordinator.userId).filter( db.and_(Coordinator.userId == user, Coordinator.password == password)).first() if not result: return jsonify({'ACK': 'FAILED', 'message': 'Wrong username/password'}) coordinator, userInfo = result user_ = userInfo.__dict__ user_.pop('_sa_instance_state') user_ = {**user_} # create a token and save it to the database sessionKey = ''.join(random.choice(string.digits) for _ in range(6)) session = Session(userId=userInfo.pecfestId, sessionKey=sessionKey) sessionKey = base64.b64encode(sessionKey.encode('ascii')).decode('utf-8') try: db.session.add(session) db.session.commit() except Exception as err: print(err) db.session.rollback() db.session.flush() return jsonify({'ACK': 'FAILED'}) return jsonify({'user': user_, 'ACK': 'SUCCESS', 'sessionKey': sessionKey})
def create(): auth_header = request.headers.get('Authorization') if auth_header: auth_token = auth_header.split(" ")[1] else: response = { 'status': 'failed', 'message': 'No authorization header found.' } return make_response(jsonify(response), 401) user_id = User.decode_auth_token(auth_token) user = User.get(User.id == user_id) if user: post_data = request.get_json() session = Session( title=post_data['title'], session_type=post_data['session_type'], description=post_data['description'], user=user.id ) if session.save(): response = { 'status': 'success', 'message': 'Session successfully saved.', 'session': { 'id': session.id, 'title': session.title, 'session_type': session.session_type } } return make_response(jsonify(response), 201) else: response = { 'status': 'failed', 'message': 'Session did not save. Try again later.' } return make_response(jsonify(response), 400) else: response = { 'status': 'failed', 'message': 'Authentication failed' } return make_response(jsonify(response), 400)
def doSignin(): usr = request.form.get('usr') pwd = request.form.get('pwd') + '!@$*&#' + usr pwd = md5(pwd.encode()) rem = request.form.get('rem') acc = Account() v = acc.getAccount( (usr,pwd.digest())) if v: res = make_response(redirect('/authen')) #set cookies token = randomStr(32) ses = Session() ret = ses.add((token, v['id'])) if rem == '1': res.set_cookie('session', token, max_age= 69 * 24 * 3600) else: res.set_cookie('session', token) return res return render_template('authen/signin.html', err = 'Sign in Failed')
def doSignin(): usr = request.form.get('usr') pwd = request.form.get('pwd') + '#$%^&*$@' + usr rem = request.form.get('rem') pwd = md5(pwd.encode()) acc = Account() v = acc.getAccount((usr, pwd.digest())) if v: res = make_response(redirect("/authen")) token = randomString(32) ses = Session() ret = ses.add((token, v['id'])) if rem == "1": res.set_cookie("session", token, max_age=30 * 3600 * 24) else: res.set_cookie("session", token) return res else: return render_template('authen/signin.html', err="Log In Failed")