Ejemplo n.º 1
0
 def get(self):
     """ Renders the Tasks page of the website """
     task_lists = models.TaskList.all()
     task_lists.filter("owner = ", common.get_current_user())
     task_lists.order("name")
     
     tasks = models.Task.all()
     tasks.filter("owner = ", common.get_current_user())
     tasks.order("due_date")
         
     self.render('tasks.html', 'tasks', {'task_lists':task_lists, 
                                         'tasks':tasks})
Ejemplo n.º 2
0
    def get(self):
        """ Renders the Create Event form to the user """
        calendars = models.Calendar.all()
        calendars.filter("owner = ", common.get_current_user())
        calendars.order("name")

        self.render('event-create.html', 'calendar', {'calendars': calendars})
Ejemplo n.º 3
0
 def get(self):
     """ Renders the Add Task form to the user """
     task_lists = models.TaskList.all()
     task_lists.filter("owner = ", common.get_current_user())
     task_lists.order("name")
     
     self.render('task-create.html', 'tasks', {'task_lists':task_lists})
Ejemplo n.º 4
0
 def get(self):
     """ Renders the Create Event form to the user """
     calendars = models.Calendar.all()
     calendars.filter("owner = ", common.get_current_user())
     calendars.order("name")
     
     self.render('event-create.html', 'calendar', {'calendars':calendars})
Ejemplo n.º 5
0
 def post(self):
     """ Processes the data from the Create Project page
     Creates a Task List and Calendar for the project
     
     """
     project = models.Project()
     project.name = cgi.escape(self.request.get('name'))
     project.owner = common.get_current_user()
     project.description = cgi.escape(self.request.get('description'))
     #members = db.ListProperty(users.User)
     project.colour = self.request.get('colour')
     project.put()
     
     # Create a Task List for the project
     tl = models.TaskList()
     tl.name = project.name
     tl.owner = project.owner
     tl.description = project.description
     tl.project = project.key()
     tl.colour = project.colour
     tl.put()
     
     # Create a calendar for the project
     calendar = models.Calendar()
     calendar.owner = project.owner
     calendar.name = project.name
     calendar.share_type = "hybrid"
     calendar.colour = project.colour
     calendar.visible = True
     calendar.put()
     
     #self.redirect('/projects/view/%s' % (project.key()))
     self.redirect('/projects')
Ejemplo n.º 6
0
 def get(self):
     """ Renders the Projects page of the Schedule-Pro website """
     projects = models.Project.all()
     projects.filter("owner = ", common.get_current_user())
     projects.order("name")
     
     self.render('projects.html', 'projects', {'projects': projects})
Ejemplo n.º 7
0
 def get(self):
     projects = models.Project.all()
     projects.filter("owner = ", common.get_current_user())
     projects.order("name")
     
     rand_col = common.get_rand_colour()
     self.render('list-create.html', 'tasks', {'rand_col':rand_col,
                                               'projects':projects})
Ejemplo n.º 8
0
 def get(self, tl_key):
     """ Renders the Modify Task List form to the user """
     tl = db.get(tl_key)
     
     projects = models.Project.all()
     projects.filter("owner = ", common.get_current_user())
     projects.order("name")
     
     self.render('list-modify.html', 'tasks', {'projects':projects, 'tl':tl})
Ejemplo n.º 9
0
 def get(self):
     """ Renders the Create Calendar page of the website """
     projects = models.Project.all()
     projects.filter("owner = ", common.get_current_user())
     projects.order("name")
     
     rand_col = common.get_rand_colour()
     self.render('calendar-create.html', 'calendar', {'rand_col':rand_col,
                                               'projects':projects})
Ejemplo n.º 10
0
 def get(self, event_key):
     """ Render the Modify Event form to the user """
     event = db.get(event_key)
     
     calendars = models.Calendar.all()
     calendars.filter("owner = ", common.get_current_user())
     calendars.order("name")
     
     self.render('event-modify.html', 'calendar', {'event':event,
                                               'calendars':calendars})
Ejemplo n.º 11
0
 def get(self, cal_key):
     """ Renders the Modify Calendar form to the user """
     calendar = db.get(cal_key)
     
     projects = models.Project.all()
     projects.filter("owner = ", common.get_current_user())
     projects.order("name")
     
     self.render('calendar-modify.html', 'calendar', {'projects':projects,
                                               'calendar':calendar})
Ejemplo n.º 12
0
    def get(self):
        """ Renders the Create Calendar page of the website """
        projects = models.Project.all()
        projects.filter("owner = ", common.get_current_user())
        projects.order("name")

        rand_col = common.get_rand_colour()
        self.render('calendar-create.html', 'calendar', {
            'rand_col': rand_col,
            'projects': projects
        })
Ejemplo n.º 13
0
 def post(self, proj_key):
     """ Processes the data from the Edit Project page """ 
     project = db.get(proj_key)
     project.name = self.request.get('name')
     project.owner = common.get_current_user()
     project.description = self.request.get('description')
     project.colour = self.request.get('colour')
     project.put()
     
     #members = db.ListProperty(users.User)
     #self.redirect('/projects/view/%s' % (proj_key))
     self.redirect('/projects')
Ejemplo n.º 14
0
    def get(self, event_key):
        """ Render the Modify Event form to the user """
        event = db.get(event_key)

        calendars = models.Calendar.all()
        calendars.filter("owner = ", common.get_current_user())
        calendars.order("name")

        self.render('event-modify.html', 'calendar', {
            'event': event,
            'calendars': calendars
        })
Ejemplo n.º 15
0
    def get(self, cal_key):
        """ Renders the Modify Calendar form to the user """
        calendar = db.get(cal_key)

        projects = models.Project.all()
        projects.filter("owner = ", common.get_current_user())
        projects.order("name")

        self.render('calendar-modify.html', 'calendar', {
            'projects': projects,
            'calendar': calendar
        })
Ejemplo n.º 16
0
 def post(self):
     #user = users.get_current_user()
     
     #account_query = db.GqlQuery("SELECT * FROM UserAccount where user= :1", user)
     #account = account_query.get()
     account = common.get_current_user()
     account.first_name = self.request.get("first_name")
     account.last_name = self.request.get("last_name")
     #account.user = user
     account.put()
     self.redirect("/")
     
     
Ejemplo n.º 17
0
 def get(self, task_key):
     """ Show the Modify Task form to the user """
     task = db.get(task_key)
     
     task_lists = models.TaskList.all()
     task_lists.filter("owner = ", common.get_current_user())
     task_lists.order("name")
     
     tasks = models.Task.all()
     tasks.filter("task_list = ", task.task_list.key())
     tasks.order("name")     
     
     self.render('task-modify.html', 'tasks', 
                 {'task_lists':task_lists, 'tasks':tasks, 'task': task})
Ejemplo n.º 18
0
    def render(self,
               template_filename,
               app='',
               template_args=None,
               check_reg=True):
        """ A function to render a page view using Google App Engine
        
        render(str, str, str, dict) -> webpage
        template_filename - string containing the template html filename
        app - string: calendar, tasks or projects
        template_args - dictionary of template variables
                
        """

        user = users.get_current_user()
        #uaq = db.GqlQuery("SELECT * FROM UserAccount where user= :1", user)
        #ua = uaq.get()
        ua = common.get_current_user()

        if user and not ua:
            # If user logged in, but they have no account, redirect them to the
            # create account page
            if check_reg:
                self.redirect('/accounts/create')
        if user and ua:
            # User is logged in, and they have an account
            user_message = "Welcome, %s | <a href=\"%s\">Logout</a>" % \
                            (ua.first_name, users.create_logout_url("/"))
        else:
            # No logged in user
            user_message = "<a href=\"%s\">Login or Register</a>" % \
                            (users.create_login_url("/"))

        # Set up template_args if template does not define any
        if template_args is None:
            template_args = {}

        # Template arguments common for all pages
        template_args['current_uri'] = self.request.uri
        template_args['user'] = user
        template_args['ua'] = ua
        template_args['is_admin'] = users.is_current_user_admin()
        template_args['user_message'] = user_message

        # Set up the template filepath
        template_file = os.path.join(os.path.dirname(__file__), 'templates',
                                     app, template_filename)

        self.response.out.write(template.render(template_file, template_args))
Ejemplo n.º 19
0
    def render(self, template_filename, app='', 
               template_args=None, check_reg=True):
        """ A function to render a page view using Google App Engine
        
        render(str, str, str, dict) -> webpage
        template_filename - string containing the template html filename
        app - string: calendar, tasks or projects
        template_args - dictionary of template variables
                
        """

        user = users.get_current_user()
        #uaq = db.GqlQuery("SELECT * FROM UserAccount where user= :1", user)
        #ua = uaq.get()
        ua = common.get_current_user()
        
        
        if user and not ua:
            # If user logged in, but they have no account, redirect them to the
            # create account page
            if check_reg:
                self.redirect('/accounts/create')
        if user and ua:
            # User is logged in, and they have an account
            user_message = "Welcome, %s | <a href=\"%s\">Logout</a>" % \
                            (ua.first_name, users.create_logout_url("/"))
        else:
            # No logged in user
            user_message = "<a href=\"%s\">Login or Register</a>" % \
                            (users.create_login_url("/"))

        # Set up template_args if template does not define any
        if template_args is None:
            template_args = {}
        
        # Template arguments common for all pages
        template_args['current_uri'] = self.request.uri
        template_args['user'] = user
        template_args['ua'] = ua
        template_args['is_admin'] = users.is_current_user_admin()
        template_args['user_message'] = user_message
        
        # Set up the template filepath
        template_file = os.path.join(os.path.dirname(__file__), 'templates', 
                                app, template_filename)
        
        self.response.out.write(template.render(template_file, template_args))
Ejemplo n.º 20
0
 def post(self):
     """ Process the new Task data, to store in the database """
     task_name = cgi.escape(self.request.get('task_name'))
     due_date = datetime.strptime(self.request.get('due_date'), '%Y-%m-%d')
     start_date = datetime.strptime(self.request.get('start_date'), '%Y-%m-%d')
     task_list = db.Key(self.request.get('task_list'))
     percent_complete = int(self.request.get('complete'))
     
     # Save the data to the database
     task = models.Task()
     task.owner = common.get_current_user()
     task.name = task_name
     task.task_list = task_list
     task.due_date = due_date
     task.start_date = start_date
     task.percent_complete = percent_complete
     task.put()
     
     # Redirect the user to the task view page after saving the new task
     self.redirect('/tasks/task/view/%s' % (task.key()))
Ejemplo n.º 21
0
 def post(self, tl_key):
     """ Process the new Task List data, to store in the database """
     tl_name = cgi.escape(self.request.get('tl_name'))
     description = cgi.escape(self.request.get('description'))
     colour = cgi.escape(self.request.get('colour'))
     
     try:
         project = db.key(self.request.get('project'))
     except AttributeError:
         # Set project to None, as project was set to 'none' by user
         project = None
                 
     # Save the data to the database
     tl = db.get(tl_key)
     tl.owner = common.get_current_user()
     tl.name = tl_name
     tl.description = description
     tl.project = project
     tl.colour = colour
     tl.put()
     
     # Redirect the user to the Task view page after saving the task
     self.redirect('/tasks')
Ejemplo n.º 22
0
 def post(self, cal_key):
     """ Process the new Calendar data, to store in the database """
     name = cgi.escape(self.request.get('name'))
     share_type = self.request.get('share_type')
     colour = cgi.escape(self.request.get('colour'))
     
     try:
         project = db.key(self.request.get('project'))
     except AttributeError:
         # Set project to None, as project was set to 'none' by user
         project = None
             
     # Save the data to the database
     calendar = db.get(cal_key)
     calendar.owner = common.get_current_user()
     calendar.name = name
     calendar.share_type = share_type
     calendar.colour = colour
     calendar.visible = calendar.visible
     calendar.project = project
     calendar.put()
     
     # Redirect the user to the Calendar page after saving the calendar
     self.redirect('/calendar')
Ejemplo n.º 23
0
    def post(self, cal_key):
        """ Process the new Calendar data, to store in the database """
        name = cgi.escape(self.request.get('name'))
        share_type = self.request.get('share_type')
        colour = cgi.escape(self.request.get('colour'))

        try:
            project = db.key(self.request.get('project'))
        except AttributeError:
            # Set project to None, as project was set to 'none' by user
            project = None

        # Save the data to the database
        calendar = db.get(cal_key)
        calendar.owner = common.get_current_user()
        calendar.name = name
        calendar.share_type = share_type
        calendar.colour = colour
        calendar.visible = calendar.visible
        calendar.project = project
        calendar.put()

        # Redirect the user to the Calendar page after saving the calendar
        self.redirect('/calendar')
Ejemplo n.º 24
0
 def get(self):
     """ Renders the Calendar page of the website """
     calendars = models.Calendar.all()
     calendars.filter("owner = ", common.get_current_user())
     calendars.order("name")
     self.render('calendar.html', 'calendar', {'calendars': calendars})
Ejemplo n.º 25
0
def leave_workspace(workspace_id):
    """Exit from a member of the workspace - ワークスペースのメンバーから抜けます

    Args:
        workspace_id (int): workspace ID

    Returns:
        Response: HTTP Respose
    """
    app_name = multi_lang.get_text("EP020-0001", "ワークスペース情報:")
    exec_stat = multi_lang.get_text("EP020-0010", "退去")
    error_detail = ""

    try:
        globals.logger.debug('#' * 50)
        globals.logger.debug('CALL {} workspace_id [{}]'.format(inspect.currentframe().f_code.co_name, workspace_id))
        globals.logger.debug('#' * 50)

        # ヘッダ情報 header info
        post_header = {
            'Content-Type': 'application/json',
        }

        api_info_epai = "{}://{}:{}".format(os.environ["EPOCH_EPAI_API_PROTOCOL"], 
                                            os.environ["EPOCH_EPAI_API_HOST"], 
                                            os.environ["EPOCH_EPAI_API_PORT"])
        
        realm_name = "exastroplatform"
        
        # ユーザIDの取得 get user id
        user_id = common.get_current_user(request.headers)
        
        # 指定のワークスペースIDに対する、オーナーロールのユーザ一覧を取得 Get a list of owner role users for the specified workspace ID
        response = requests.get("{}/{}/client/epoch-system/roles/{}/users".format(api_info_epai, realm_name, const.ROLE_WS_OWNER[0].format(workspace_id)), headers=post_header)

        users = json.loads(response.text)
        globals.logger.debug(type(users["rows"]))
        globals.logger.debug(users["rows"])
        
        owner_check = False
        
        # 自身がオーナーかどうか確認 Check if you are the owner
        for user in users["rows"]:
            if user["user_id"] == user_id:
                owner_check = True
                break

        if owner_check:
            # 自身がオーナの場合、他のオーナーがいるかチェック If you are the owner, check if there are other owners
            if len(users["rows"]) == 1:
                # ログイン者が唯一のオーナーの時は退去できない Can't move out when the login person is the only owner
                return jsonify({"result": "400", "reason": multi_lang.get_text("EP020-0014", "あなた以外のオーナーがいないので退去できません")}), 400

        response = requests.get("{}/{}/user/{}/roles/epoch-system".format(api_info_epai, realm_name, user_id), headers=post_header)
        
        user_roles = json.loads(response.text)
        
        roles = []
        
        for role in user_roles["rows"]:            
            if "ws-{}".format(workspace_id) in role["name"]:
                roles.append(
                    {
                        "name" : role["name"]
                    }
                )
            
        post_data = {
            "roles" :  roles
        }
        
        globals.logger.debug("post_data : " + json.dumps(post_data))
        
        # 自分自身のワークスペースに関するロールを全て削除 - Delete all roles related to your own workspace
        response = requests.delete("{}/{}/user/{}/roles/epoch-system".format(api_info_epai, realm_name, user_id), headers=post_header, data=json.dumps(post_data))
        
        
        if response.status_code != 200:
            error_detail = multi_lang.get_text("EP020-0011", "ユーザクライアントロールの削除に失敗しました")
            return jsonify({"result": "400", "reason": multi_lang.get_text("EP020-0015", "ワークスペースからの退去に失敗しました")}), 400
    
        # ロールの更新日を現在時刻に変更 - Change the update date of the role to the current time
        api_info = "{}://{}:{}/workspace/{}".format(os.environ["EPOCH_RS_WORKSPACE_PROTOCOL"], 
                                                    os.environ["EPOCH_RS_WORKSPACE_HOST"], 
                                                    os.environ["EPOCH_RS_WORKSPACE_PORT"],
                                                    workspace_id)
        
        # 現在時刻を設定はrs_workspace側で処理 The current time is set on the rs_workspace side
        post_data = {
            'role_update_at' : ''
        }
        
        response = requests.patch(api_info, headers=post_header, data=json.dumps(post_data))
        
        if response.status_code != 200:
            error_detail = multi_lang.get_text("EP020-0012", "ロール更新日の変更に失敗しました")
            return jsonify({"result": "400", "reason": multi_lang.get_text("EP020-0015", "ワークスペースからの退去に失敗しました")}), 400

        return jsonify({"result": "200"}), 200

    except common.UserException as e:
        return common.server_error_to_message(e, app_name + exec_stat, error_detail)
    except Exception as e:
        return common.server_error_to_message(e, app_name + exec_stat, error_detail)
Ejemplo n.º 26
0
def merge_workspace_members(workspace_id):
    """ワークスペース該当メンバー登録 workspace member registration

    Request: json
        {
            "rows": [
                {
                    "user_id": "",
                    "roles": [
                        {
                            "kind": "",
                        }
                    ]
                },
            ],
            "role_update_at": "",
        }

    Returns:
        Response: HTTP Respose
    """

    app_name = multi_lang.get_text("EP020-0003", "ワークスペース情報:")
    exec_stat = multi_lang.get_text("EP020-0005", "メンバー登録")
    error_detail = ""
    return_code = 500

    try:
        globals.logger.debug('#' * 50)
        globals.logger.debug('CALL {}'.format(inspect.currentframe().f_code.co_name))
        globals.logger.debug('#' * 50)

        # 引数はJSON形式 Arguments are in JSON format
        req_json = request.json.copy()

        # ヘッダ情報 header info.
        post_headers = {
            'Content-Type': 'application/json',
        }

        # workspace get
        api_url = "{}://{}:{}/workspace/{}".format(os.environ['EPOCH_RS_WORKSPACE_PROTOCOL'],
                                                    os.environ['EPOCH_RS_WORKSPACE_HOST'],
                                                    os.environ['EPOCH_RS_WORKSPACE_PORT'],
                                                    workspace_id)
        response = requests.get(api_url, headers=post_headers)

        if response.status_code == 200 and common.is_json_format(response.text):
            # 取得したワークスペース情報を退避 Save the acquired workspace information
            ret = json.loads(response.text)
            ws_row = ret["rows"][0]
        elif response.status_code == 404:
            return_code = 400
            error_detail = multi_lang.get_text("EP000-0022", "更新対象(workspace)がありません", "workspace")
            # 情報取得できない場合はエラー Error if information cannot be obtained
            raise common.UserException("{} not found workspace !".format(inspect.currentframe().f_code.co_name))
        else:
            if response.status_code == 500 and common.is_json_format(response.text):
                # 戻り値がJsonの場合は、値を取得 If the return value is Json, get the value
                ret = json.loads(response.text)
                # 詳細エラーがある場合は詳細を設定 Set details if there are detailed errors
                if ret["errorDetail"] is not None:
                    error_detail = ret["errorDetail"]

            raise common.UserException("{} Error get workspace db status:{}".format(inspect.currentframe().f_code.co_name, response.status_code))

        globals.logger.debug("Exclusive check")
        globals.logger.debug("db[{}] update[{}]".format(str(ws_row["role_update_at"]), req_json["role_update_at"]))
        # 排他チェック:ロール更新日時が一致しているかチェックする
        # Exclusive check: Check if the role update datetime match
        if str(ws_row["role_update_at"]) != req_json["role_update_at"]:
            return_code = 400
            error_detail = multi_lang.get_text("EP000-0023", "対象の情報(workspace)が他で更新されたため、更新できません\n画面更新後、再度情報を入力・選択して実行してください", "workspace")
            raise common.UserException("{} update exclusive check error".format(inspect.currentframe().f_code.co_name))

        ret_status = response.status_code

        # ログインユーザーの情報取得 Get login user information
        user_id = common.get_current_user(request.headers)

        api_url = "{}://{}:{}/{}/user/{}".format(os.environ['EPOCH_EPAI_API_PROTOCOL'],
                                                os.environ['EPOCH_EPAI_API_HOST'],
                                                os.environ['EPOCH_EPAI_API_PORT'],
                                                os.environ["EPOCH_EPAI_REALM_NAME"],
                                                user_id
                                            )
        #
        # get users - ユーザー取得
        #
        response = requests.get(api_url)
        if response.status_code != 200 and response.status_code != 404:
            error_detail = multi_lang.get_text("EP020-0008", "ユーザー情報の取得に失敗しました")
            raise common.UserException("{} Error user get status:{}".format(inspect.currentframe().f_code.co_name, response.status_code))

        users = json.loads(response.text)
        # globals.logger.debug(f"users:{users}")

        # 取得したユーザーのロールを取得 
        # Get the role of the acquired user
        api_url = "{}://{}:{}/{}/user/{}/roles/epoch-system".format(os.environ['EPOCH_EPAI_API_PROTOCOL'],
                                                                os.environ['EPOCH_EPAI_API_HOST'],
                                                                os.environ['EPOCH_EPAI_API_PORT'],
                                                                os.environ["EPOCH_EPAI_REALM_NAME"],
                                                                user_id
                                                        )

        #
        # get user role - ユーザーロール情報取得
        #
        response = requests.get(api_url)
        if response.status_code != 200:
            error_detail = multi_lang.get_text("EP020-0009", "ユーザーロール情報の取得に失敗しました")
            globals.logger.debug(error_detail)
            raise common.UserException("{} Error user role get status:{}".format(inspect.currentframe().f_code.co_name, response.status_code))

        ret_roles = json.loads(response.text)
        # globals.logger.debug(f"roles:{ret_roles}")

        bool_owener_role = False
        # オーナーロール設定可能権限かどうかチェックする 
        # Check if the owner role can be set
        for get_role in ret_roles["rows"]:
            # globals.logger.debug('role:{}'.format(get_role["name"]))
            # ロールがあればチェックOK
            # Check OK if there is a roll
            if get_role["name"] == const.ROLE_WS_ROLE_OWNER_ROLE_SETTING[0].format(workspace_id):
                bool_owener_role = True
                break

        # 権限「オーナー変更」保有しているユーザーを抽出する 
        # Extract users who have the authority "change owner"
        owener_users = api_service_common.get_workspace_members_by_role(workspace_id, const.ROLE_WS_ROLE_OWNER_ROLE_SETTING[0].format(workspace_id))
        # globals.logger.debug(f"owener_users{owener_users}")
        owener_users_id_array = []
        # チェック用に配列化
        # Arranged for checking
        for user in owener_users:
            owener_users_id_array.append(user["user_id"])

        # オーナーロール変更以外がオーナーロールありに変更したかチェック
        # Check if other than the owner role change has changed to have an owner role
        if not bool_owener_role:
            bool_auth_error = False
            for row in req_json["rows"]:
                globals.logger.debug(f"req_row:{row}")
                bool_owner_update = False
                for role in row["roles"]:
                    # オーナー更新ありのフラグをONにする 
                    # Turn on the flag with owner update
                    globals.logger.debug("owener_check({}):({})".format(common.get_role_name(role["kind"]), const.ROLE_WS_OWNER[0]))
                    if common.get_role_name(role["kind"]) == const.ROLE_WS_OWNER[0]:
                        bool_owner_update = True

                    # オーナーロールの変更がある場合、権限がないのでエラーとする
                    # If there is a change in the owner role, it will be an error because you do not have the authority.
                    if common.get_role_name(role["kind"]) == const.ROLE_WS_OWNER[0] and \
                        row["user_id"] not in owener_users_id_array:
                        bool_auth_error = True
                        break

                # オーナーありのユーザーからオーナー権限を削除した際は権限がないのでエラーとする
                # If you delete the owner authority from a user who has an owner, you will get an error because you do not have the authority.
                if not bool_owner_update and row["user_id"] in owener_users_id_array:
                    bool_auth_error = True
                    break

                # 権限エラーの場合は、処理を抜ける 
                # In case of permission error, exit the process
                if bool_auth_error:
                    break

            # 権限エラー
            # Permission error
            if bool_auth_error:
                # ログイン者が唯一のオーナーの時は退去できない 
                # Can't move out when the login person is the only owner
                error_detail = multi_lang.get_text("EP020-0024", "オーナー権限を変更することはできません")
                raise common.AuthException(error_detail)

        else:
            # オーナーロール変更ありのユーザーが、オーナーロール変更した際、オーナーロールのユーザーが残るかどうか
            # Check if a user with an owner role change has a user change with an owner role change
            owner_add_cnt = 0
            owner_del_cnt = 0
            for row in req_json["rows"]:
                bool_owner_update = False
                for role in row["roles"]:
                    # オーナー更新ありのフラグをONにする 
                    # Turn on the flag with owner update
                    if common.get_role_name(role["kind"]) == const.ROLE_WS_OWNER[0]:
                        bool_owner_update = True
                        break

                # オーナーありのユーザーからオーナー権限を削除した件数をカウント
                # Count the number of cases where the owner authority is deleted from the owner-owned user
                if not bool_owner_update and row["user_id"] in owener_users_id_array:
                    owner_del_cnt += 1
                # 新規オーナーかチェックする
                # Check if you are a new owner
                elif bool_owner_update and row["user_id"] not in owener_users_id_array:
                    owner_add_cnt += 1

            # オーナーが0人となる場合はエラーとする
            # If the number of owners is 0, an error will occur.
            if (len(owener_users) - owner_del_cnt) == 0 and owner_add_cnt == 0:
                # ログイン者が唯一のオーナーの時は退去できない
                # Can't move out when the login person is the only owner
                error_detail = multi_lang.get_text("EP020-0025", "最低1人以上のオーナーは必要です")
                raise common.AuthException(error_detail)


        for row in req_json["rows"]:

            # 登録前にすべてのroleを削除する 
            # Delete all roles before registration
            roles = const.ALL_ROLES
            #
            # ロールの制御のurl - role control url
            #
            api_url = "{}://{}:{}/{}/user/{}/roles/epoch-system".format(os.environ['EPOCH_EPAI_API_PROTOCOL'],
                                                                    os.environ['EPOCH_EPAI_API_HOST'],
                                                                    os.environ['EPOCH_EPAI_API_PORT'],
                                                                    os.environ["EPOCH_EPAI_REALM_NAME"],
                                                                    row["user_id"],
                                                            )

            del_roles = []
            for role in roles:
                del_role = {
                    "name": role.format(workspace_id),
                }
                del_roles.append(del_role)

            post_data = {
                "roles" : del_roles
            }

            #
            # delete workspace role - ワークスペース ロールの削除
            #
            response = requests.delete(api_url, headers=post_headers, data=json.dumps(post_data))
            if response.status_code != 200:
                error_detail = multi_lang.get_text("EP020-0006", "ロールの削除に失敗しました")
                raise common.UserException("{} Error user role delete status:{}".format(inspect.currentframe().f_code.co_name, response.status_code))

            # 登録するroleの情報を編集 
            # Edit the information of the role to be registered
            add_roles = []
            for role in row["roles"]:
                add_role = {
                    "name": common.get_role_name(role["kind"]).format(workspace_id),
                    "enabled": True,
                }
                add_roles.append(add_role)
            
            post_data = {
                "roles" : add_roles
            }

            #
            # append workspace role - ワークスペース ロールの付与
            #
            response = requests.post(api_url, headers=post_headers, data=json.dumps(post_data))
            if response.status_code != 200:
                error_detail = multi_lang.get_text("EP020-0007", "ロールの登録に失敗しました")
                globals.logger.debug(error_detail)
                raise common.UserException("{} Error user role add status:{}".format(inspect.currentframe().f_code.co_name, response.status_code))


            #
            # logs output - ログ出力
            #
            post_data = {
                "action" : "role update",
                "role_update_user_id" : row["user_id"],
                "role_update_user_roles" : add_roles,
            }

            api_url = "{}://{}:{}/workspace/{}/member/{}/logs/{}".format(os.environ['EPOCH_RS_LOGS_PROTOCOL'],
                                                        os.environ['EPOCH_RS_LOGS_HOST'],
                                                        os.environ['EPOCH_RS_LOGS_PORT'],
                                                        workspace_id,
                                                        users["info"]["username"],
                                                        const.LOG_KIND_UPDATE
                                                        )

            response = requests.post(api_url, headers=post_headers, data=json.dumps(post_data))
            if response.status_code != 200:
                error_detail = multi_lang.get_text("EP020-0023", "ログ出力に失敗しました")
                globals.logger.debug(error_detail)
                raise common.UserException("{} Error log output status:{}".format(inspect.currentframe().f_code.co_name, response.status_code))

            #
            # workspace info. Roll update date update - ワークスペース情報 ロール更新日の更新
            #
            post_data = {
                "role_update_at" : "",
            }

            globals.logger.debug("role datetime update Start")
            api_url = "{}://{}:{}/workspace/{}".format(os.environ['EPOCH_RS_WORKSPACE_PROTOCOL'],
                                                        os.environ['EPOCH_RS_WORKSPACE_HOST'],
                                                        os.environ['EPOCH_RS_WORKSPACE_PORT'],
                                                        workspace_id)
            response = requests.patch(api_url, headers=post_headers, data=json.dumps(post_data))
            if response.status_code != 200:
                error_detail = multi_lang.get_text("EP000-0024", "対象の情報({})を更新できませんでした", "workspace")
                globals.logger.debug(error_detail)
                raise common.UserException("{} Error workspace-db update status:{}".format(inspect.currentframe().f_code.co_name, response.status_code))

            globals.logger.debug("role datetime update Succeed!")

        return jsonify({"result": "200"}), 200

    except common.AuthException as e:
        return jsonify({"result": 400, "errorDetail": error_detail}), 400
    except common.UserException as e:
        return common.user_error_to_message(e, app_name + exec_stat, error_detail, return_code)
    except Exception as e:
        return common.server_error_to_message(e, app_name + exec_stat, error_detail)
Ejemplo n.º 27
0
 def get(self):
     #user = users.get_current_user()
     #uaq = db.GqlQuery("SELECT * FROM UserAccount where user= :1", user)
     #ua = uaq.get()
     ua = common.get_current_user()
     self.render("account-modify.html", "account", {'account':ua})
Ejemplo n.º 28
0
def user_get():
    """ユーザー情報取得 user info get

    Returns:
        dict: user info.
    """

    try:
        globals.logger.debug('#' * 50)
        globals.logger.debug('CALL {}'.format(
            inspect.currentframe().f_code.co_name))
        globals.logger.debug('#' * 50)

        user_id = common.get_current_user(request.headers)

        api_url = "{}://{}:{}/{}/user/{}".format(
            os.environ['EPOCH_EPAI_API_PROTOCOL'],
            os.environ['EPOCH_EPAI_API_HOST'],
            os.environ['EPOCH_EPAI_API_PORT'],
            os.environ["EPOCH_EPAI_REALM_NAME"], user_id)
        #
        # get users - ユーザー取得
        #
        response = requests.get(api_url)
        if response.status_code != 200 and response.status_code != 404:
            error_detail = multi_lang.get_text("EP020-0008",
                                               "ユーザー情報の取得に失敗しました")
            raise common.UserException("{} Error user get status:{}".format(
                inspect.currentframe().f_code.co_name, response.status_code))

        users = json.loads(response.text)
        # globals.logger.debug(f"users:{users}")

        # 取得したユーザーのロールを取得 Get the role of the acquired user
        api_url = "{}://{}:{}/{}/user/{}/roles/epoch-system".format(
            os.environ['EPOCH_EPAI_API_PROTOCOL'],
            os.environ['EPOCH_EPAI_API_HOST'],
            os.environ['EPOCH_EPAI_API_PORT'],
            os.environ["EPOCH_EPAI_REALM_NAME"], user_id)

        #
        # get user role - ユーザーロール情報取得
        #
        response = requests.get(api_url)
        if response.status_code != 200:
            error_detail = multi_lang.get_text("EP020-0009",
                                               "ユーザーロール情報の取得に失敗しました")
            raise common.UserException(
                "{} Error user role get status:{}".format(
                    inspect.currentframe().f_code.co_name,
                    response.status_code))

        ret_roles = json.loads(response.text)
        # globals.logger.debug(f"roles:{ret_roles}")

        sorted_roles = sorted(ret_roles["rows"], key=lambda x: x['name'])
        # globals.logger.debug(f"sorted_roles:{sorted_roles}")

        stock_workspace_id = []
        set_role_display = []
        ret_role = ""
        all_roles = []
        all_composite_roles = []
        workspace_name = None
        # 取得したすべてのロールから絞り込む Narrow down from all acquired roles
        for get_role in sorted_roles:
            role_info = common.get_role_info(get_role["name"])
            # 該当のロールのみチェック Check only the corresponding role
            if role_info is not None:
                # 同じロールは退避しない Do not save the same role
                if get_role["name"] not in all_roles:
                    all_roles.append(get_role["name"])

                ex_role = re.match("ws-({}|\d+)-(.+)", get_role["name"])
                globals.logger.debug("role_workspace_id:{} kind:{}".format(
                    ex_role[1], ex_role[2]))

                # ワークスペースは重複があるので、1回のみ抽出 Workspaces are duplicated, so extract only once
                # ただし、1回目は設定しない However, do not set the first time
                if ex_role[
                        1] not in stock_workspace_id and workspace_name is not None:
                    # 並んでいる要素をソート Sort the elements in a row
                    set_role_display.sort()
                    # ソート用の文字列カット String cut for sorting
                    role_display = [s[3:] for s in set_role_display]
                    # workspace_id が 変わった際にレコード化 Record when workspace_id changes
                    ret_role = ret_role + ',"{}":["{}"]'.format(
                        workspace_name, '","'.join(role_display))
                    set_role_display = []

                # 取得したロール名を配列にする Make the acquired role name into an array
                set_role_display.append(
                    f"{role_info[3]:02}:" +
                    multi_lang.get_text(role_info[1], role_info[2]))

                workspace_id = ex_role[1]
                stock_workspace_id.append(workspace_id)
                # workspace get
                api_url = "{}://{}:{}/workspace/{}".format(
                    os.environ['EPOCH_RS_WORKSPACE_PROTOCOL'],
                    os.environ['EPOCH_RS_WORKSPACE_HOST'],
                    os.environ['EPOCH_RS_WORKSPACE_PORT'], workspace_id)

                response = requests.get(api_url)
                if response.status_code != 200:
                    error_detail = multi_lang.get_text("EP020-0013",
                                                       "ワークスペース情報の取得に失敗しました")
                    raise common.UserException(
                        "{} Error workspace get status:{}".format(
                            inspect.currentframe().f_code.co_name,
                            response.status_code))

                ret_ws = json.loads(response.text)
                workspace_name = ret_ws["rows"][0]["common"]["name"]
                # workspace name empty to set fix name
                if len(workspace_name) == 0:
                    workspace_name = multi_lang.get_text("EP000-0025", "名称未設定")
            else:
                # 同じ子ロールは退避しない Do not save the same composite role
                if get_role["name"] not in all_composite_roles:
                    all_composite_roles.append(get_role["name"])

        # 並んでいる要素をソート Sort the elements in a row
        set_role_display.sort()
        # ソート用の文字列カット String cut for sorting
        role_display = [s[3:] for s in set_role_display]

        ret_role = ret_role + ',"{}":["{}"]'.format(workspace_name,
                                                    '","'.join(role_display))
        ret_role = "{" + ret_role[1:] + "}"

        ret_user = {
            "user_id": user_id,
            "username": users["info"]["username"],
            "enabled": users["info"]["enabled"],
            "firstName": users["info"]["firstName"],
            "lastName": users["info"]["lastName"],
            "email": users["info"]["email"],
            "role": ret_role,
            "roles": all_roles,
            "composite_roles": all_composite_roles,
        }
        # globals.logger.debug(f"ret_user:{ret_user}")

        return ret_user

    except common.UserException as e:
        raise
    except Exception as e:
        raise
Ejemplo n.º 29
0
 def get(self):
     """ Renders the Calendar page of the website """
     calendars = models.Calendar.all()
     calendars.filter("owner = ", common.get_current_user())
     calendars.order("name")
     self.render('calendar.html', 'calendar', {'calendars': calendars})