Пример #1
0
    def get(self):
        id = request.values.get('id', None)
        email = request.values.get('email', None)

        if email:
            response = UserService().get_user_by_email(email)
        else:
            response = UserService().get_user(id)
        return response, HTTPStatus.OK
Пример #2
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)
Пример #3
0
    async def register_srp(self, request, context):
        # check exist user
        try:
            email = request.email
            display_name = request.display_name
            password_verifier = request.password_verifier
            salt = request.salt
            iv_parameter = request.iv_parameter

            exists_user = self.service.get_user_by_email(email)
            if exists_user:
                raise Exception(Message.REGISTER_USER_ALREADY_EXISTS)

            # register new user
            new_user_id = self.service.register_srp_user(
                email, password_verifier, display_name)

            if new_user_id:
                # create new user in database
                UserService().create_new_user_srp(new_user_id, email,
                                                  password_verifier, salt,
                                                  iv_parameter, display_name,
                                                  'account')
            else:
                self.service.delete_user(new_user_id)
                raise Exception(Message.REGISTER_USER_FAILED)
            try:
                SignalService().peer_register_client_key(
                    new_user_id, request.client_key_peer)
            except Exception:
                self.service.delete_user(new_user_id)
                UserService().delete_user(new_user_id)
                raise Exception(Message.REGISTER_USER_FAILED)

            return auth_messages.RegisterSRPRes()

        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_USER_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)
Пример #4
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)
Пример #5
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)
Пример #6
0
 def __init__(self, *kwargs):
     self.service = UserService()
 def __init__(self, *args, **kwargs):
     self.user_service = UserService()
Пример #8
0
 def post(self):
     payload = request.json
     saved_id = UserService().save(payload)
     return {"id": saved_id}, HTTPStatus.OK
Пример #9
0
 async def reset_pincode(self, request, context):
     try:
         success_status = self.service.verify_hash_pre_access_token(
             request.user_name, request.reset_pincode_token,
             "verify_pincode")
         exists_user = self.service.get_user_by_email(request.user_name)
         if not exists_user:
             raise Exception(Message.USER_NOT_FOUND)
         if not success_status:
             raise Exception(Message.REGISTER_CLIENT_SIGNAL_KEY_FAILED)
         self.user_service.change_password(request, None,
                                           request.hash_pincode,
                                           exists_user["id"])
         old_client_key_peer = SignalService().peer_get_client_key(
             exists_user["id"])
         SignalService().client_update_peer_key(exists_user["id"],
                                                request.client_key_peer)
         try:
             salt, iv_parameter = UserService().update_hash_pin(
                 exists_user["id"], request.hash_pincode, request.salt,
                 request.iv_parameter)
         except Exception as e:
             logger.error(e)
             SignalService().client_update_peer_key(exists_user["id"],
                                                    old_client_key_peer)
             raise Message.get_error_object(
                 Message.REGISTER_CLIENT_SIGNAL_KEY_FAILED)
         client_key_obj = request.client_key_peer
         client_key_peer = auth_messages.PeerGetClientKeyResponse(
             clientId=exists_user["id"],
             workspace_domain=get_owner_workspace_domain(),
             registrationId=client_key_obj.registrationId,
             deviceId=client_key_obj.deviceId,
             identityKeyPublic=client_key_obj.identityKeyPublic,
             preKeyId=client_key_obj.preKeyId,
             preKey=client_key_obj.preKey,
             signedPreKeyId=client_key_obj.signedPreKeyId,
             signedPreKey=client_key_obj.signedPreKey,
             signedPreKeySignature=client_key_obj.signedPreKeySignature,
             identityKeyEncrypted=client_key_obj.identityKeyEncrypted)
         # logout all device before get new token for user after updated new key
         user_sessions = KeyCloakUtils.get_sessions(
             user_id=exists_user["id"])
         for user_session in user_sessions:
             KeyCloakUtils.remove_session(session_id=user_session['id'])
         token = self.service.token(request.user_name, request.hash_pincode)
         introspect_token = KeyCloakUtils.introspect_token(
             token['access_token'])
         return auth_messages.AuthRes(
             workspace_domain=get_owner_workspace_domain(),
             workspace_name=get_system_config()['server_name'],
             access_token=token["access_token"],
             expires_in=token['expires_in'],
             refresh_expires_in=token['refresh_expires_in'],
             refresh_token=token['refresh_token'],
             token_type=token['token_type'],
             session_state=token['session_state'],
             scope=token['scope'],
             salt=salt,
             client_key_peer=client_key_peer,
             iv_parameter=iv_parameter)
     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)
Пример #10
0
 async def register_pincode(self, request, context):
     try:
         exists_user = self.service.get_user_by_email(request.user_name)
         if not exists_user:
             raise Exception(Message.REGISTER_CLIENT_SIGNAL_KEY_FAILED)
         user_info = self.user_service.get_user_by_id(exists_user["id"])
         if user_info.password_verifier is not None:
             raise Exception(Message.REGISTER_USER_ALREADY_EXISTS)
         salt = request.salt
         self.user_service.change_password(request, None,
                                           request.hash_pincode,
                                           exists_user['id'])
         # using hash_pincode as password for social user
         try:
             SignalService().peer_register_client_key(
                 exists_user['id'], request.client_key_peer)
         except Exception as e:
             logger.error(e)
         try:
             UserService().update_hash_pin(exists_user['id'],
                                           request.hash_pincode,
                                           request.salt,
                                           request.iv_parameter)
         except Exception as e:
             logger.error(e)
             ## TODO: revert change_password
             SignalService().delete_client_peer_key(exists_user['id'])
             raise Message.get_error_object(
                 Message.REGISTER_CLIENT_SIGNAL_KEY_FAILED)
         require_action = ""
         client_key_obj = request.client_key_peer
         client_key_peer = auth_messages.PeerGetClientKeyResponse(
             clientId=exists_user['id'],
             workspace_domain=get_owner_workspace_domain(),
             registrationId=client_key_obj.registrationId,
             deviceId=client_key_obj.deviceId,
             identityKeyPublic=client_key_obj.identityKeyPublic,
             preKeyId=client_key_obj.preKeyId,
             preKey=client_key_obj.preKey,
             signedPreKeyId=client_key_obj.signedPreKeyId,
             signedPreKey=client_key_obj.signedPreKey,
             signedPreKeySignature=client_key_obj.signedPreKeySignature,
             identityKeyEncrypted=client_key_obj.identityKeyEncrypted)
         token = self.service.token(request.user_name, request.hash_pincode)
         introspect_token = KeyCloakUtils.introspect_token(
             token['access_token'])
         self.user_service.update_last_login(
             user_id=introspect_token['sub'])
         return auth_messages.AuthRes(
             workspace_domain=get_owner_workspace_domain(),
             workspace_name=get_system_config()['server_name'],
             access_token=token["access_token"],
             expires_in=token['expires_in'],
             refresh_expires_in=token['refresh_expires_in'],
             refresh_token=token['refresh_token'],
             token_type=token['token_type'],
             session_state=token['session_state'],
             scope=token['scope'],
             salt=request.salt,
             client_key_peer=client_key_peer,
             iv_parameter=request.iv_parameter)
     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)
Пример #11
0
    async def forgot_password_update(self, request, context):
        try:
            logger.info("from email {}".format(request.email))
            user_info = self.user_service.get_user_by_auth_source(
                request.email, "account")
            old_user_id = user_info.id
            self.service.verify_hash_pre_access_token(old_user_id,
                                                      request.pre_access_token,
                                                      "forgot_password")
            new_user_id = self.service.forgot_user(request.email,
                                                   request.password_verifier,
                                                   user_info.display_name)
            try:
                await GroupService().forgot_peer_groups_for_client(user_info)
            except Exception as e:
                logger.error("cannot send notify to other group")
                logger.error(e)
            SignalService().delete_client_peer_key(old_user_id)
            if new_user_id:
                # create new user in database
                UserService().forgot_user(user_info, new_user_id,
                                          request.password_verifier,
                                          request.salt, request.iv_parameter)
            else:
                self.service.delete_user(new_user_id)
                raise Exception(Message.REGISTER_USER_FAILED)
            try:
                SignalService().peer_register_client_key(
                    new_user_id, request.client_key_peer)
            except Exception:
                self.service.delete_user(new_user_id)
                UserService().delete_user(new_user_id)
                raise Exception(Message.REGISTER_USER_FAILED)

            token = self.service.token(request.email,
                                       request.password_verifier)
            if token:
                client_key_obj = request.client_key_peer
                client_key_peer = auth_messages.PeerGetClientKeyResponse(
                    clientId=new_user_id,
                    workspace_domain=get_owner_workspace_domain(),
                    registrationId=client_key_obj.registrationId,
                    deviceId=client_key_obj.deviceId,
                    identityKeyPublic=client_key_obj.identityKeyPublic,
                    preKeyId=client_key_obj.preKeyId,
                    preKey=client_key_obj.preKey,
                    signedPreKeyId=client_key_obj.signedPreKeyId,
                    signedPreKey=client_key_obj.signedPreKey,
                    signedPreKeySignature=client_key_obj.signedPreKeySignature,
                    identityKeyEncrypted=client_key_obj.identityKeyEncrypted)
                self.user_service.update_last_login(user_id=new_user_id)
                auth_message = auth_messages.AuthRes(
                    workspace_domain=get_owner_workspace_domain(),
                    workspace_name=get_system_config()['server_name'],
                    access_token=token['access_token'],
                    expires_in=token['expires_in'],
                    refresh_expires_in=token['refresh_expires_in'],
                    refresh_token=token['refresh_token'],
                    token_type=token['token_type'],
                    session_state=token['session_state'],
                    scope=token['scope'],
                    salt=request.salt,
                    client_key_peer=client_key_peer,
                    iv_parameter=request.iv_parameter)
            else:
                raise Exception(Message.AUTH_USER_NOT_FOUND)
            return auth_message

        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.CHANGE_PASSWORD_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)
Пример #12
0
 def __init__(self, *kwargs):
     self.service = AuthService()
     self.user_service = UserService()