Ejemplo n.º 1
0
 def __generate_api_token(self, admin):
     token_issue_date = self.util.get_now()
     valid_period = timedelta(minutes=self.util.safe_get_config("login.token_valid_time_minutes", 60))
     token_expire_date = token_issue_date + valid_period
     user_token = UserToken(
         token=str(uuid.uuid1()), user=admin, expire_date=token_expire_date, issue_date=token_issue_date
     )
     user_token.save()
     return user_token
Ejemplo n.º 2
0
 def __generate_api_token(self, admin):
     token_issue_date = self.util.get_now()
     valid_period = timedelta(minutes=self.util.safe_get_config("login.token_valid_time_minutes", 60))
     token_expire_date = token_issue_date + valid_period
     user_token = UserToken(token=str(uuid.uuid1()),
                            user=admin,
                            expire_date=token_expire_date,
                            issue_date=token_issue_date)
     user_token.save()
     return user_token
Ejemplo n.º 3
0
 def login(self, user):
     token_issue_date = datetime.utcnow()
     valid_period = timedelta(minutes=1)
     token_expire_date = token_issue_date + valid_period
     user_token = UserToken(token=str(uuid.uuid1()),
                            user=user,
                            expire_date=token_expire_date,
                            issue_date=token_issue_date)
     user_token.save()
     self.client.update_headers(dict(token=user_token.token))
     return user_token
Ejemplo n.º 4
0
    def update_user_operation_time(self):
        """Update the user's last operation time.

        :rtype:bool
        :return True if success in updating, return False if token not found or token is overtime.
        """
        if HTTP_HEADER.TOKEN not in request.headers:
            return False

        user = self.__validate_token(request.headers[HTTP_HEADER.TOKEN])
        if user is None:
            return False
        else:
            time_interval = timedelta(hours=self.util.safe_get_config("login.token_valid_time_minutes", 60))
            new_toke_time = self.util.get_now() + time_interval
            UserToken.objects(token=request.headers[HTTP_HEADER.TOKEN]).update(expire_date=new_toke_time)

        users_operation_time[user.id] = self.util.get_now()

        return True
Ejemplo n.º 5
0
    def __validate_token(self, token):
        """Validate token to make sure it exists and not expired

        :type token: str|unicode
        :param token: token strin

        :rtype: User
        :return user related to the token or None if token is invalid
        """
        if "authenticated" in g and g.authenticated:
            return g.user
        else:
            # todo eliminate the warning related to 'objects'
            t = UserToken.objects(token=token).first()
            if t and t.expire_date >= self.util.get_now():
                g.authenticated = True
                g.user = t.user
                return t.user

        return None
Ejemplo n.º 6
0
    def __validate_token(self, token):
        """Validate token to make sure it exists and not expired

        :type token: str|unicode
        :param token: token strin

        :rtype: User
        :return user related to the token or None if token is invalid
        """
        if "authenticated" in g and g.authenticated:
            return g.user
        else:
            # todo eliminate the warning related to 'objects'
            t = UserToken.objects(token=token).first()
            if t and t.expire_date >= self.util.get_now():
                g.authenticated = True
                g.user = t.user
                return t.user

        return None
Ejemplo n.º 7
0
    def authing(self, context):
        token = context.token
        username = context.username

        if not token or not username:
            self.log.info(
                "Unable to handle authing login request. Either token or username is empty. username: "******"Unable to handle authing login request. Either token or username is empty"
            )

        # validate access token
        self.log.info("Validate authing token for user %s" % username)
        validate_url = get_config("login.authing.validate_token_url") + token
        validate_raw_resp = get_remote(validate_url)
        validate_resp = json.loads(validate_raw_resp)

        if int(validate_resp["code"]) != 200 or not bool(
                validate_resp["status"]):
            self.log.info("Token invalid: %s" % validate_raw_resp)
            return unauthorized("Token invalid: %s" % validate_raw_resp)

        authing_id = context._id
        open_id = context.unionid
        provider = context.registerMethod
        if "oauth" in provider:
            # OAuth like github. registerMethod example: "oauth:github"
            provider = provider[6:]
        else:
            # Authing user: using authing_id as open_id
            open_id = authing_id

        email_list = [{
            "email": context.get("email", ""),
            "primary": True,
            "verified": bool(context.get("emailVerified", False))
        }]

        user = self.__get_existing_user(open_id, provider)
        if user is not None:
            nickname = context.get("nickname", user.nickname)
            if not nickname:
                nickname = user.name
            user.update(name=context.get("username", user.name),
                        nickname=nickname,
                        access_token=context.get("token", user.access_token),
                        avatar_url=context.get("photo", user.avatar_url),
                        authing_id=authing_id,
                        last_login_time=self.util.get_now(),
                        login_times=user.login_times + 1,
                        online=True)
            list(
                map(lambda x: self.__create_or_update_email(user, x),
                    email_list))
        else:
            user = User(openid=open_id,
                        name=username,
                        provider=provider,
                        authing_id=authing_id,
                        nickname=context.nickname,
                        access_token=token,
                        avatar_url=context.get("photo", ""),
                        login_times=int(context.get("loginsCount", "1")),
                        online=True)

            try:
                user.save()
            except ValidationError as e:
                self.log.error(e)
                return internal_server_error("create user fail.")

            list(
                map(lambda x: self.__create_or_update_email(user, x),
                    email_list))

        # save API token
        token_expire_date = self.util.get_now() + timedelta(hours=1)
        if "tokenExpiredAt" in context:
            try:
                token_expire_date = datetime.strptime(
                    context.tokenExpiredAt, '%a %b %d %Y %H:%M:%S GMT%z (CST)')
            except Exception as e:
                self.log.warn(
                    "Unable to parse tokenExpiredAt: %s. Will use 1 hour as expiry."
                    % context.tokenExpiredAt)
        else:
            self.log.info(
                "tokenExpiredAt not included in authing response. Will use 1 hour as expiry."
            )

        user_token = UserToken(token=token,
                               user=user,
                               expire_date=token_expire_date)
        user_token.save()
        # resp = {
        #     "token": user_token.dic(),
        #     "user": user.dic()
        # }
        resp = context.to_dict()
        resp.update(user.dic())
        return resp