Esempio n. 1
0
 def delete_user(self, userid):
     # delete user in keycloak server by its userid
     try:
         KeyCloakUtils.delete_user(user_id=userid)
     except Exception as e:
         logger.info(e)
         raise Exception(Message.UNAUTHENTICATED)
Esempio n. 2
0
 def register_srp_user(self, email, password_verifier, display_name):
     # register new user with using email as user name
     try:
         user_id = KeyCloakUtils.create_user(email, email,
                                             password_verifier, "",
                                             display_name)
         if user_id:
             a = KeyCloakUtils.send_verify_email(user_id)
             return user_id
     except Exception as e:
         logger.info(e)
         raise Exception(Message.REGISTER_USER_FAILED)
Esempio n. 3
0
 def forgot_user(self, email, password_verifier, display_name):
     try:
         # delete user, then re create new user with activate status is True
         old_user_id = self.get_user_by_email(email)["id"]
         self.delete_user(old_user_id)
         new_user_id = KeyCloakUtils.create_user(email, email,
                                                 password_verifier, "",
                                                 display_name)
         if new_user_id:
             KeyCloakUtils.active_user(new_user_id)
             return new_user_id
     except Exception as e:
         logger.info(e)
         raise Exception(Message.REGISTER_USER_FAILED)
Esempio n. 4
0
    async def get_user_notes(self, request, context):
        try:
            metadata = dict(context.invocation_metadata())
            access_token_information = KeyCloakUtils.introspect_token(
                metadata['access_token'])
            user_id = access_token_information['sub']
            user_notes = self.service.get_user_notes(user_id)
            return note_pb2.GetUserNotesResponse(
                user_notes=[
                    note_pb2.UserNoteResponse(
                        id=note.id,
                        title=note.title,
                        content=note.content,
                        note_type=note.note_type,
                        created_at=int(note.created_at.timestamp() * 1000))
                    for note in user_notes
                ],
                base_response=note_pb2.BaseResponse())

        except Exception as e:
            logger.error(e)
            if not e.args or e.args[0] not in Message.msg_dict:
                errors = [
                    Message.get_error_object(Message.AUTH_USER_NOT_FOUND)
                ]
            else:
                errors = [Message.get_error_object(e.args[0])]
            context.set_details(
                json.dumps(errors, default=lambda x: x.__dict__))
            context.set_code(grpc.StatusCode.INTERNAL)
Esempio n. 5
0
 def get_user_by_email(self, email):
     # get user in keycloak server by its email
     try:
         return KeyCloakUtils.get_user_by_email(email)
     except Exception as e:
         logger.info(e)
         raise Exception(Message.USER_NOT_FOUND)
Esempio n. 6
0
    def google_login(self, google_id_token):
        # google login by using google id token, return user_name, user_id and boolean variable indicate if this user is new user
        try:
            verify_id_token_url = "https://oauth2.googleapis.com/tokeninfo?id_token=" + google_id_token
            req = requests.get(url=verify_id_token_url)
            if req.status_code != 200:
                raise Exception(Message.GOOGLE_AUTH_ID_TOKEN_INVALID)
            google_token_info = req.json()

            logger.info("Google login token spec:")
            logger.info(google_token_info)

            # check google_token_info["aud"] matching with google app id
            google_app_id = get_system_config()["google_app_id"]
            if google_token_info["aud"] != google_app_id[
                    "ios"] and google_token_info["aud"] != google_app_id[
                        "android"]:
                raise Exception(Message.GOOGLE_AUTH_FAILED)

            google_email = google_token_info["email"]
            # check account exits
            user = self.get_user_by_email(email=google_email)
            #active_user
            if user:
                if not user["emailVerified"]:
                    KeyCloakUtils.active_user(user["id"])
                user_info = UserService().get_user_by_id(user["id"])
                return google_email, user[
                    "id"], user_info.password_verifier is None or user_info.password_verifier == ""
            else:
                # create new user
                new_user_id = KeyCloakUtils.create_user_without_password(
                    google_email, google_email, "", google_token_info["name"])
                new_user = UserService().create_user_social(
                    id=new_user_id,
                    email=google_email,
                    display_name=google_token_info["name"],
                    auth_source='google')
                if new_user is None:
                    self.delete_user(new_user_id)
                    raise Exception(Message.REGISTER_USER_FAILED)
                return google_email, new_user_id, True
        except Exception as e:
            logger.info(e)
            raise Exception(Message.GOOGLE_AUTH_FAILED)
Esempio n. 7
0
def _token_check(access_token):
    try:
        token_info = KeyCloakUtils.introspect_token(access_token)
        logger.info({"token info": token_info})
        if token_info['active']:
            return True
        else:
            return False
    except Exception as e:
        return False
Esempio n. 8
0
 def _fd_server_check(self, access_token):
     try:
         token_info = KeyCloakUtils.introspect_token(access_token)
         print("auth_interceptor.py => token info here=", token_info)
         if token_info['active']:
             return True
         else:
             return False
     except Exception as e:
         return False
Esempio n. 9
0
    def change_password(self, request, old_pass, new_pass, user_id):
        # change password in keycloak
        try:
            user_info = self.model.get(user_id)
            response = KeyCloakUtils.set_user_password(user_id, new_pass)

            return user_info
        except Exception as e:
            logger.info(e)
            raise Exception(Message.CHANGE_PASSWORD_FAILED)
Esempio n. 10
0
    def facebook_login(self, facebook_access_token):
        # facebook login by using facebook access token, return user_name, user_id and boolean variable indicate if this user is new user
        try:
            # validate access_token
            facebook_app_id = get_system_config()["facebook_app"]
            verify_token_app_id = "https://graph.facebook.com/debug_token?input_token={}&access_token={}|{}".format(
                facebook_access_token, facebook_app_id["app_id"],
                facebook_app_id["app_secret"])
            req = requests.get(url=verify_token_app_id)
            if req.status_code != 200:
                raise Exception(Message.FACEBOOK_ACCESS_TOKEN_INVALID)
            facebook_token_app_id_info = req.json()
            facebook_token_app_id = facebook_token_app_id_info["data"][
                "app_id"]
            if facebook_token_app_id != facebook_app_id["app_id"]:
                raise Exception(Message.FACEBOOK_ACCESS_TOKEN_INVALID)

            verify_token_url = "https://graph.facebook.com/me?fields=id,name,email&access_token=" + facebook_access_token
            req = requests.get(url=verify_token_url)

            if req.status_code != 200:
                raise Exception(Message.FACEBOOK_ACCESS_TOKEN_INVALID)
            facebook_token_info = req.json()

            logger.info("Facebook login token spec:")
            logger.info(facebook_token_info)

            facebook_id = facebook_token_info["id"]
            facebook_email = facebook_token_info["email"]
            facebook_name = facebook_token_info["name"]
            # check account exits
            user = self.get_user_by_email(facebook_id)
            if user:
                user_info = UserService().get_user_by_id(user["id"])
                return facebook_id, user[
                    "id"], user_info.password_verifier is None or user_info.password_verifier == ""
            else:
                # create new user
                new_user_id = KeyCloakUtils.create_user_without_password(
                    facebook_email, facebook_id, "", facebook_name)
                new_user = UserService().create_user_social(
                    id=new_user_id,
                    email=facebook_email,
                    display_name=facebook_name,
                    auth_source='facebook')
                if new_user is None:
                    self.delete_user(new_user_id)
                    raise Exception(Message.REGISTER_USER_FAILED)
                return facebook_id, new_user_id, True
        except Exception as e:
            logger.info(e)
            raise Exception(Message.FACEBOOK_AUTH_FAILED)
Esempio n. 11
0
 def token(self, user_name, password):
     # basic authen service for login with user_name and password
     try:
         token = KeyCloakUtils.token(user_name, password)
         if token:
             return token
     except Exception as e:
         logger.info(e)
         response_code = e.response_code
         check_error = json.loads(e.args[0]).get("error")
         if check_error == "invalid_grant" and response_code == 400:
             raise Exception(Message.USER_NOT_VERIFY_EMAIL)
         raise Exception(Message.AUTH_USER_NOT_FOUND)
Esempio n. 12
0
 async def get_joined_groups(self, request, context):
     try:
         header_data = dict(context.invocation_metadata())
         introspect_token = KeyCloakUtils.introspect_token(header_data['access_token'])
         client_id = introspect_token['sub']
         obj_res = self.service.get_joined_group(client_id)
         return obj_res
     except Exception as e:
         logger.error(e)
         if not e.args or e.args[0] not in Message.msg_dict:
             errors = [Message.get_error_object(Message.REGISTER_CLIENT_SIGNAL_KEY_FAILED)]
         else:
             errors = [Message.get_error_object(e.args[0])]
         context.set_details(json.dumps(
             errors, default=lambda x: x.__dict__))
         context.set_code(grpc.StatusCode.INTERNAL)
Esempio n. 13
0
    def office_login(self, office_access_token):
        # office login by using office access token, return user_name, user_id and boolean variable indicate if this user is new user
        try:
            verify_token_url = "https://graph.microsoft.com/v1.0/me"
            bearer = 'Bearer ' + office_access_token
            headers = {'Authorization': bearer}

            req = requests.get(url=verify_token_url, headers=headers)
            if req.status_code != 200:
                raise Exception(Message.OFFICE_ACCESS_TOKEN_INVALID)
            office_token_info = req.json()

            logger.info("Office login token spec:")
            logger.info(office_token_info)

            office_id = office_token_info["id"]
            # check account exits
            user = self.get_user_by_email(office_id)
            if user:
                user_info = UserService().get_user_by_id(user["id"])
                return office_id, user[
                    "id"], user_info.password_verifier is None or user_info.password_verifier == ""
            else:
                display_name = office_token_info["displayName"]
                email = ""
                if not display_name:
                    if office_token_info["userPrincipalName"]:
                        user_principal_name = office_token_info[
                            "userPrincipalName"].split("@")
                        if len(user_principal_name) > 0:
                            display_name = user_principal_name[0]
                            email = office_token_info["userPrincipalName"]
                # create new user
                new_user_id = KeyCloakUtils.create_user_without_password(
                    email, office_id, "", display_name)
                new_user = UserService().create_user_social(
                    id=new_user_id,
                    email=office_token_info["mail"],
                    display_name=display_name,
                    auth_source='office')
                if new_user is None:
                    self.delete_user(new_user_id)
                    raise Exception(Message.REGISTER_USER_FAILED)
                return office_id, new_user_id, True
        except Exception as e:
            logger.info(e)
            raise Exception(Message.OFFICE_AUTH_FAILED)
Esempio n. 14
0
    async def edit_note(self, request, context):
        try:
            metadata = dict(context.invocation_metadata())
            access_token_information = KeyCloakUtils.introspect_token(
                metadata['access_token'])
            user_id = access_token_information['sub']
            self.service.edit_note(request.note_id, request.title,
                                   request.content, request.note_type, user_id)
            return note_pb2.BaseResponse()

        except Exception as e:
            logger.error(e)
            if not e.args or e.args[0] not in Message.msg_dict:
                errors = [
                    Message.get_error_object(Message.AUTH_USER_NOT_FOUND)
                ]
            else:
                errors = [Message.get_error_object(e.args[0])]
            context.set_details(
                json.dumps(errors, default=lambda x: x.__dict__))
            context.set_code(grpc.StatusCode.INTERNAL)
Esempio n. 15
0
    async def get_group(self, request, context):
        try:
            header_data = dict(context.invocation_metadata())
            introspect_token = KeyCloakUtils.introspect_token(header_data['access_token'])
            client_id = introspect_token['sub']
            group_id = request.group_id
            obj_res = self.service.get_group(group_id, client_id)

            if obj_res is not None:
                return obj_res
            else:
                raise Exception(Message.GROUP_CHAT_NOT_FOUND)
        except Exception as e:
            logger.error(e)
            if not e.args or e.args[0] not in Message.msg_dict:
                errors = [Message.get_error_object(Message.GET_GROUP_CHAT_FAILED)]
            else:
                errors = [Message.get_error_object(e.args[0])]
            context.set_details(json.dumps(
                errors, default=lambda x: x.__dict__))
            context.set_code(grpc.StatusCode.INTERNAL)
Esempio n. 16
0
 def logout(self, refresh_token):
     # basic authen service for logout using refresh_token
     try:
         KeyCloakUtils.logout(refresh_token)
     except Exception as e:
         logger.info(e)