Пример #1
0
def createSession(user):
    salt = Salt()
    timestamp = str(int(math.floor(time.time())))
    sessionPassword = salt.hash(str(user['uid']) + "|" + timestamp)
    session = UserSession(uid=user['uid'], session_password=sessionPassword)
    session.save()
    return sessionPassword
Пример #2
0
def login(email, password):
    try:
        user = User.query.filter_by(email=email).first()
        if user.check_password_hash(password):
            uuid = str(uuid4())
            print(uuid)
            # Set expiration date to one week
            expiration_date = datetime.datetime.now() + datetime.timedelta(
                days=7)
            user_session = UserSession(session_id=uuid,
                                       user_id=user.id,
                                       expiration_date=expiration_date)
            db.session.add(user_session)
            db.session.commit()
            return jsonify(id=user.id,
                           username=user.username,
                           email=user.email,
                           first_name=user.first_name,
                           last_name=user.last_name,
                           create_date=user.create_date,
                           token=uuid)
        else:
            return 'Password Incorrect'

    except Exception as e:
        return 'Error: {}'.format(e)
Пример #3
0
def auth(request):
    response_data = {}
    success = 0
    if request.method == 'POST':
        uemail = request.POST['email']

        # TODO: Encrypt PIN.
        upin = request.POST['pin']

        try:
            u = User.objects.get(email__iexact=uemail, pin=upin)
            existing_session = UserSession.objects.filter(user=u)
            if len(existing_session) == 0:
                sessionid = str(uuid.uuid4())

                us = UserSession()
                us.user = u
                us.session_id = sessionid
                us.save()
                response_data['sessionid'] = sessionid
                response_data['userid'] = u.sysid
            else:
                response_data['sessionid'] = existing_session[0].session_id
                response_data['userid'] = u.sysid

            success = 1
        except User.DoesNotExist:
            pass  # TODO: Log failure

    response_data['success'] = success
    return render_to_json(response_data)
Пример #4
0
def _save_token(user_profile):
    token = user_profile['auth_token']
    user_session = UserSession(user_profile['id'],
        token,
        datetime.utcnow() + SESSION_DURATION)
    try:
        db.session.add(user_session)
        db.session.commit()
    except sqlalchemy.exc.IntegrityError:
        # a session for this token is already in DB, just update it
        db.session.rollback()
        _udpate_session(token)
Пример #5
0
def check_session(user_id, state):
    # if user_id in db check for mode and state
    userSessionObject = database.get_session_by_userid(user_id)

    # if not in db, add in new user session
    if not userSessionObject:
        userSessionObject = UserSession(user_id=user_id, state=NO_STATE)
        database.add_session(userSessionObject)

    if userSessionObject.state == state:
        return userSessionObject
    
    return False
Пример #6
0
    def test_remove_session_for_user(self, app):
        # given
        user_id = 1
        session_id = uuid.uuid4()

        session = UserSession()
        session.userId = user_id
        session.uuid = session_id
        PcObject.save(session)

        # when
        delete_user_session(user_id, session_id)

        # then
        assert UserSession.query.count() == 0
Пример #7
0
    def post(self):
        json = request.get_json(force=True)
        username = json['username']
        password = json['password']

        qry = User.query.filter(User.username == username).first()

        if qry is None:
            return jsonify(status=False, message="Incorrect credentials!")

        if not verify_password(password, qry.password):
            return jsonify(status=False, message="Incorrect credentials!")

        token = generate_session_token(50)
        new_login = UserSession.UserSession(agent_id=qry.agent_id,
                                            session_token=token)
        db.session.add(new_login)
        db.session.commit()
        return jsonify(status=True, token=token)
    def create_session(self, user_id=None):
        """Overloading

        :param user_id: Default value = None)

        """
        if user_id is None:
            return None
        session_id = super(SessionDBAuth, self).create_session(user_id)
        if session_id is None:
            return None
        user_session = UserSession()
        user_session.user_id = user_id
        user_session.session_id = session_id
        try:
            db_session.add(user_session)
            db_session.commit()
        except BaseException:
            return None
        return session_id
Пример #9
0
    def post(self):

        username = self.request.data.get("username")
        password = self.request.data.get("password")
        
        if not username or not password:
            raise HTTP_400("Please specify username and password")

        # See if a user exists with those params
        user = db.query(User).filter(
            User.username==username, 
            User.password==password).first()
        if not user:
            raise HTTP_401("Invalid username or password")
       
        # Create a new session 
        sess = UserSession(
            user_id=user.id)
        db.add(sess)
        self.response.set_cookie("session_id", sess.session_id) 
        return { "message":"Logged in", "session_id":sess.session_id }
Пример #10
0
def login_view(request):
    if request.method == 'POST':
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user = UserProfile.objects.filter(username=login_form.cleaned_data['username']).first()
            if user:
                if check_password(login_form.cleaned_data['password'], user.password):
                    session = UserSession(user=user)
                    session.create_session_token()
                    session.save()
                    response = redirect('/feed/')
                    response.set_cookie(key='session_token', value=session.session_token)
                    return response
                else:
                    ctypes.windll.user32.MessageBoxW(0, u"Password does not match.Please try again", u"Error", 0)
                    login_form = SignUpForm()
            else:
                ctypes.windll.user32.MessageBoxW(0, u"User does not exit.Please signup", u"Error", 0)
                login_form = SignUpForm()
    elif request.method == 'GET':
        login_form = LoginForm()
    return render(request, 'login.html', {'form': login_form})
Пример #11
0
 def login(self):
     username = self.POST.get("username")
     password = self.POST.get("password")
     try:
         user = db_session.session.query(User).filter(
             User.username == username,
             User.pass_hash == User.hash_password(password),
         ).one()
     except NoResultFound:
         self.send_response(302)
         self.send_header('Location', "/login")
         self.end_headers()
         return
     cookie = http.cookies.SimpleCookie()
     user_session = UserSession(user=username)
     db_session.session.add(user_session)
     db_session.session.commit()
     cookie["session"] = f"{user_session.id}-{user_session.uid}"
     self.send_response(302)
     for data in cookie.values():
         self.send_header("Set-Cookie", data.OutputString())
     self.send_header('Location', "/")
     self.end_headers()
def register_user_session(user_id: int, session_uuid: UUID):
    session = UserSession()
    session.userId = user_id
    session.uuid = session_uuid
    PcObject.save(session)
Пример #13
0
    def create_user_session(user_id, jti):
        new_user_session = UserSession(user_id=user_id, jti=jti)
        session.add(new_user_session)
        session.commit()

        return new_user_session
Пример #14
0
def check_new_user(user_id):
    userSessionObject = database.get_session_by_userid(user_id)

    if not userSessionObject:
        userSessionObject = UserSession(user_id=user_id, state=NO_STATE)
        database.add_session(userSessionObject)