Exemplo n.º 1
0
 def define_tables(self):
     """Defines the auth_user table"""
     db = self.db
     Field = db.Field
     if not "auth_user" in db.tables:
         ne = IS_NOT_EMPTY()
         if self.password_complexity:
             requires = [IS_STRONG(**self.password_complexity), CRYPT()]
         else:
             requires = [CRYPT()]
         auth_fields = [
             Field(
                 "email",
                 requires=(IS_EMAIL(), IS_NOT_IN_DB(db, "auth_user.email")),
                 unique=True,
             ),
             Field(
                 "password",
                 "password",
                 requires=requires,
                 readable=False,
                 writable=False,
             ),
             Field("first_name", requires=ne),
             Field("last_name", requires=ne),
             Field("profile_pic", default="https://merriam-webster.com/assets/mw/images/article/art-wap-landing-mp-lg/[email protected]"),
             Field("sso_id", readable=False, writable=False),
             Field("action_token", readable=False, writable=False),
             Field(
                 "last_password_change",
                 "datetime",
                 default=None,
                 readable=False,
                 writable=False,
             ),
         ]
         if self.use_username:
             auth_fields.insert(
                 0,
                 Field(
                     "username",
                     requires=[ne, IS_NOT_IN_DB(db, "auth_user.username")],
                     unique=True,
                 ),
             )
         if self.use_phone_number:
             auth_fields.insert(
                 2,
                 Field(
                     "phone_number",
                     requires=[
                         ne,
                         IS_MATCH(r"^[+]?(\(\d+\)|\d+)(\(\d+\)|\d+|[ -])+$"),
                     ],
                 ),
             )
         if self.block_previous_password_num is not None:
             auth_fields.append(
                 Field("past_passwords_hash", "list:string", writable=False, readable=False))
         db.define_table("auth_user", *auth_fields, *self.extra_auth_user_fields)
Exemplo n.º 2
0
 def define_tables(self):
     """Defines the auth_user table"""
     db = self.db
     Field = db.Field
     if not "auth_user" in db.tables:
         ne = IS_NOT_EMPTY()
         if self.password_complexity:
             requires = [IS_STRONG(**self.password_complexity), CRYPT()]
         else:
             requires= [CRYPT()]
         auth_fields = [
             Field(
                 "email",
                 requires=(IS_EMAIL(), IS_NOT_IN_DB(db, "auth_user.email")),
                 unique=True,
             ),
             Field(
                 "password",
                 "password",
                 requires=requires,
                 readable=False,
                 writable=False,
             ),
             Field("first_name", requires=ne),
             Field("last_name", requires=ne),
             Field("sso_id", readable=False, writable=False),
             Field("action_token", readable=False, writable=False),
             Field(
                 "last_password_change",
                 "datetime",
                 default=None,
                 readable=False,
                 writable=False,
             ),
         ]
         if self.use_username:
             auth_fields.insert(
                 0,
                 Field(
                     "username",
                     requires=[ne, IS_NOT_IN_DB(db, "auth_user.username")],
                     unique=True,
                 ),
             )
         if self.use_phone_number:
             auth_fields.insert(
                 2,
                 Field(
                     "phone_number",
                     requires=[
                         ne,
                         IS_MATCH(r"^[+]?(\(\d+\)|\d+)(\(\d+\)|\d+|[ -])+$"),
                     ],
                 ),
             )
         if self.block_previous_password_num is not None:
             auth_fields.append(
                 Field("past_passwords_hash", "list:string", writable=False, readable=False))
         db.define_table("auth_user", *auth_fields, *self.extra_auth_user_fields)
Exemplo n.º 3
0
 def change_password(self, user, new_password, password=None, check=True):
     db = self.db
     if check:
         pwd = CRYPT()(password)[0]
         if not pwd == user.password:
             return {"errors": {"old_password": "******"}}
         new_pwd, error = db.auth_user.password.validate(new_password)
         if error:
             return {"errors": {"new_password": error}}
         if new_pwd == user.password:
             return {
                 "errors": {
                     "new_password": "******"
                 }
             }
         if self.block_previous_password_num:
             past_pwds = (user.past_passwords_hash or [])[
                 : self.block_previous_password_num
             ]
             if any(new_pwd == old_pwd for old_pwd in past_pwds):
                 return {"errors": {"new_password": "******"}}
             else:
                 past_pwds.insert(0, pwd)
                 db(db.auth_user.id == user.id).update(past_passwords_hash=past_pwds)
     num = db(db.auth_user.id == user.id).update(
         password=new_pwd, last_password_change=datetime.datetime.utcnow()
     )
     return {"updated": num}
Exemplo n.º 4
0
Arquivo: auth.py Projeto: misl6/py4web
 def login(self, email, password):
     db = self.db
     if "email_auth" in self.plugins:
         email = email.lower()
         if self.plugins["email_auth"].validate_credentials(email, password):
             user = db(db.auth_user.email == email).select().first()
             return (user, None)
         else:
             return None, "Invalid Credentials"
     else:
         value = email.lower()
         if self.use_username:
             query = (
                 (db.auth_user.email == value)
                 if "@" in value
                 else (db.auth_user.username == value)
             )
         else:
             query = db.auth_user.email == value
         user = db(query).select().first()
         if not user:
             return (None, "Invalid email")
         if (user.action_token or "").startswith("pending-registration:"):
             return (None, "Registration is pending")
         if user.action_token == "account-blocked":
             return (None, "Account is blocked")
         if user.action_token == "pending-approval":
             return (None, "Account needs to be approved")
         if CRYPT()(password)[0] == user.password:
             return (user, None)
         return None, "Invalid Credentials"
Exemplo n.º 5
0
 def define_tables(self):
     """Defines the auth_user table"""
     db = self.db
     Field = db.Field
     if not "auth_user" in db.tables:
         ne = IS_NOT_EMPTY()
         auth_fields = [
             Field(
                 "email",
                 requires=(IS_EMAIL(), IS_NOT_IN_DB(db, "auth_user.email")),
                 unique=True,
             ),
             Field(
                 "password",
                 "password",
                 requires=CRYPT(),
                 readable=False,
                 writable=False,
             ),
             Field("first_name", requires=ne),
             Field("last_name", requires=ne),
             Field("sso_id", readable=False, writable=False),
             Field("action_token", readable=False, writable=False),
         ]
         if self.use_username:
             auth_fields.insert(
                 0,
                 Field(
                     "username",
                     requires=[ne, IS_NOT_IN_DB(db, "auth_user.username")],
                     unique=True,
                 ),
             )
         db.define_table("auth_user", *auth_fields, *self.extra_auth_user_fields)
Exemplo n.º 6
0
 def change_email(self, user, new_email, password=None, check=True):
     db = self.db
     if check and not CRYPT()(password)[0] == user.get("password"):
         return {"errors": {"password": "******"}}
     return (
         db(db.auth_user.id == user.get("id"))
         .validate_and_update(email=new_email)
         .as_dict()
     )
Exemplo n.º 7
0
 def login():
     if MODE == 'demo':
         valid = True
     else:
         password = request.json.get('password')
         valid = password and CRYPT()(password)[0] == os.environ['WEB3PY_PASSWORD']
     if valid:
         session['user'] = dict(id=1)
     return dict(user=valid, mode=MODE)
Exemplo n.º 8
0
def define_table(db):
    db.define_table(
        "auth_user",
        Field("user_name"),
        Field("user_password", requires=CRYPT()),
        Field("user_email"),
        Field("user_phone"),
        Field("reg_time", type="datetime"),
    )
    pass
Exemplo n.º 9
0
def login():
    valid = False
    password = request.json.get('password')
    password_file = os.environ.get('PY4WEB_PASSWORD_FILE')
    if password and password_file and os.path.exists(password_file):
        with open(password_file, 'r') as fp:
            encrypted_password = fp.read().strip()
            valid = CRYPT()(password)[0] == encrypted_password
    if valid:
        session['user'] = dict(id=1)
    return dict(user=valid, app='v3p')
Exemplo n.º 10
0
 def login():
     if MODE == "demo":
         valid = True
     else:
         valid = False
         password = request.json.get("password")
         password_file = os.environ.get("PY4WEB_PASSWORD_FILE")
         if password and password_file and os.path.exists(password_file):
             with open(password_file, "r") as fp:
                 encrypted_password = fp.read().strip()
                 valid = CRYPT()(password)[0] == encrypted_password
     if valid:
         session["user"] = dict(id=1)
     return dict(user=valid, mode=MODE)
Exemplo n.º 11
0
 def define_tables(self):
     db = self.db
     Field = db.Field
     if not 'auth_user' in db.tables:
         ne = IS_NOT_EMPTY()
         db.define_table(
             'auth_user',
             Field('email', requires=(IS_EMAIL(), IS_NOT_IN_DB(db, 'auth_user.email')), unique=True),
             Field('password','password', requires=CRYPT(), readable=False),
             Field('first_name', requires=ne),
             Field('last_name', requires=ne),
             Field('sso_id', editable=False, readable=False),
             Field('action_token', editable=False, readable=False),
             *self.extra_auth_user_fields)
Exemplo n.º 12
0
async def login(
    data: OAuth2PasswordRequestForm = Depends(),
):  # , response_class=RedirectResponse
    # ideally we would put back the response_class parameter but its
    # just a hint to the doc system and right now causing the docs
    # to crash.  Added to an issue for FastAPI on github.
    # ):
    """
    This is called as the result of a login form being submitted.
    If authentication is successful an access token is created and stored
    in a session cookie.  This session cookie is used for all protected routes.
    The ``auth_manager`` is provided by `../session.py` which also explains how
    to setup a protected route.
    """
    username = data.username
    password = data.password

    rslogger.debug(f"username = {username}")
    user = await load_user(username)
    rslogger.debug(user)
    # um = UserManagerWeb2Py()
    if not user:
        # raise InvalidCredentialsException
        return RedirectResponse("/auth/login")
    else:
        rslogger.debug(f"Got a user {user.username} check password")
        # The password in the web2py database is formatted as follows:
        # alg$salt$hash
        # We need to grab the salt and provide that to the CRYPT function
        # which we import from pydal for now.  Once we are completely off of
        # web2py then this will change. The ``web2py_private_key`` is an environment
        # variable that comes from the ``private/auth.key`` file.
        salt = user.password.split("$")[1]
        crypt = CRYPT(key=settings.web2py_private_key, salt=salt)
        crypted_password = str(crypt(password)[0])
        if crypted_password != user.password:
            raise InvalidCredentialsException

    access_token = auth_manager.create_access_token(
        data={"sub": user.username}, expires=timedelta(hours=12)
    )
    redirect_to = f"/books/published/{user.course_name}/index.html"
    rslogger.debug(f"Sending user to {redirect_to}")
    response = RedirectResponse(redirect_to)
    # *Important* We need to set the cookie here for the redirect in order for
    # the next page to validate.  This will also set the cookie in the browser
    # for future pages.
    auth_manager.set_cookie(response, access_token)
    return response
Exemplo n.º 13
0
async def create_user(user: AuthUserValidator) -> Optional[AuthUserValidator]:
    """
    The given user will have the password in plain text.  First we will hash
    the password then add this user to the database.
    """
    if await fetch_user(user.username):
        raise HTTPException(
            status_code=422,
            detail=http_422error_detail(["body", "username"],
                                        "duplicate username",
                                        "integrity_error"),
        )

    new_user = AuthUser(**user.dict())
    crypt = CRYPT(key=settings.web2py_private_key, salt=True)
    new_user.password = str(crypt(user.password)[0])
    async with async_session.begin() as session:
        session.add(new_user)
    return AuthUserValidator.from_orm(new_user)
Exemplo n.º 14
0
 def define_tables(self):
     """Defines the auth_user table"""
     db = self.db
     Field = db.Field
     if not 'auth_user' in db.tables:
         ne = IS_NOT_EMPTY()
         auth_fields = [
             Field('email', requires=(IS_EMAIL(), IS_NOT_IN_DB(db, 'auth_user.email')), unique=True),
             Field('password','password', requires=CRYPT(), readable=False, writable=False),
             Field('first_name', requires=ne),
             Field('last_name', requires=ne),
             Field('sso_id', readable=False, writable=False),
             Field('action_token', readable=False, writable=False),
         ]
         if self.use_username:
             auth_fields.insert(
                 0, Field('username', requires=[ne, IS_NOT_IN_DB(db, 'auth_user.username')], unique=True))
         db.define_table(
             'auth_user',
             *auth_fields,
             *self.extra_auth_user_fields)
Exemplo n.º 15
0
def authenticate():
    username, password = request.json.get("email"), request.json.get("password")
    #print(username)
    #print(password)

    try:
        # authenticate against auth_user table
        query = db.auth_user.email == username
        user = db(query).select().first()
        if CRYPT()(password)[0] != user.password:
            return json.dumps({'error': 403, 'message': 'Authentication failed for: %s' % (username)})
    except:
        return json.dumps({'error': 403, 'message': 'Authentication failed for %s: ' % (username)})

    data = {}
    data['username'] = username
    data['email'] = user.email
    data['first_name'] = user.first_name
    data['last_name'] = user.last_name
    data['exp'] = datetime.utcnow() + timedelta(seconds=1200)
    token = jwt.encode(data, 'secret', algorithm='HS256')

    print(token)
    return json.dumps({'token': token})