Exemplo n.º 1
0
 def update(self, request):
     template = self.view.get_template('hook/update.html')
     repo = Repo.retrieve(name=request.params['repo'])
     if (repo.owner.object != request.user
             and not InnerPermission.is_accepted('update_repository',
                                                 repo.owner, request.user)):
         return Response.redirect(
             self.app.convert_url('/' + request.params['repo'] + '/hook'))
     error = ''
     if request.method == 'POST':
         form = HookCreateForm(request.post())
         shutil.move(
             self.app.project_dir / 'repos/{}.git/hooks/{}'.format(
                 repo.name, request.params['hook']), self.app.project_dir /
             'repos/{}.git/hooks/{}'.format(repo.name, form['name']))
         with open(
                 self.app.project_dir /
                 'repos/{}.git/hooks/{}'.format(repo.name, form['name']),
                 'w') as f:
             f.write(form['code'])
         return Response.redirect(
             self.app.convert_url('/{}/hook/{}'.format(
                 repo.name, form['name'])))
     with open(self.app.project_dir / 'repos/{}.git/hooks/{}'.format(
             repo.name, request.params['hook'])) as f:
         code = f.read()
     return Response.render(
         template, {
             'repo': repo,
             'name': request.params['hook'],
             'code': code,
             'error': error
         })
Exemplo n.º 2
0
 def update_profile(self, req):
     template = self.view.get_template("user/update/profile.html")
     user = User.retrieve(screen_name=req.params["id"])
     roles = Role.list()
     error = ""
     if req.method == "POST":
         try:
             form = UserUpdateForm(req.post())
             user.screen_name = form["screen_name"]
             user.name = form["name"]
             user.icon = (resize_icon(form["icon"])
                          if form["icon"] is not None else user.icon)
             roles_ = []
             for role in form["roles"]:
                 roles_.append(Role.retrieve(role))
             user.roles = roles_
             user.update()
             return Response.redirect(
                 self.app.convert_url("/users/" + user.screen_name +
                                      "/settings"))
         except Exception as err:
             error = str(err)
     return Response.render(
         template,
         {
             "user": user,
             "screen_name": user.screen_name,
             "name": user.name,
             "icon": user.icon,
             "roles": roles,
             "error": error
         },
     )
Exemplo n.º 3
0
 def handle(self, request):
     if not is_admin(request.user):
         return Response.redirect(self.app.convert_url('/'))
     error = ""
     if request.method == "POST":
         try:
             form = SettingsForm(request.post())
             for screen_name, permission_roles in form['permission'].items(
             ):
                 permission = InnerPermission.retrieve(
                     screen_name=screen_name)
                 permission.roles = [
                     InnerRole.retrieve(screen_name=role)
                     for role in permission_roles
                 ]
                 permission.update()
             error = "変更を保存しました"
         except Exception as err:
             error = str(err)
     template = self.view.get_template('settings.html')
     return Response.render(
         template, {
             "roles": InnerRole.list(),
             "permissions": InnerPermission.list(),
             "error": error
         })
Exemplo n.º 4
0
 def update_notification(self, req):
     template = self.view.get_template("user/update/notification.html")
     user = User.retrieve(screen_name=req.params["id"])
     if user._id != req.user._id:
         return Response.redirect(self.app.convert_url("/"))
     error = ""
     if req.method == "POST":
         try:
             form = SubscriptionForm(req.post())
             if form["action"] == "subscribe":
                 subscription = PushSubscription()
                 subscription.subscription = form["subscription"]
                 subscription.create()
                 user.subscriptions.append(subscription)
                 user.update()
                 error = "通知の購読を設定しました"
             else:
                 subscription = PushSubscription.retrieve(
                     subscription=form["subscription"])
                 subscription.delete()
                 error = "通知の購読を解除しました"
         except Exception as err:
             error = str(err)
     return Response.render(
         template,
         {
             "user": user,
             "vapid_public_key": self.app.project.vapid["public_key"],
             "error": error
         },
     )
Exemplo n.º 5
0
 def create(self, request):
     template = self.view.get_template('merge/create.html')
     repo = Repo.retrieve(name=request.params['repo'])
     error = ""
     if request.method == "POST":
         try:
             form = MergeCreateForm(request.post())
             merge = Merge()
             merge.base = form['base']
             merge.compare = form['compare']
             merge.title = form['title']
             merge.body = form['body']
             merge.repo = repo
             merge.user = request.user
             merge.create()
             return Response.redirect(
                 self.app.convert_url('/' + repo.name + '/merge/' +
                                      merge._id))
         except Exception as err:
             error = str(err)
     return Response.render(template, {
         "repo": repo,
         "entity": repo.entity,
         "error": error
     })
Exemplo n.º 6
0
 def create(self, request):
     template = self.view.get_template("repo/create.html")
     nodes = [*Group.list(), *User.list()]
     try:
         if request.method == 'POST':
             body = request.post()
             repo = Repo()
             repo.name = body['name']
             repo.owner = Node.retrieve(body['owner'])
             repo.create()
             if not (self.app.project_dir / 'git_template').is_dir:
                 git.Repo.init(self.app.project_dir / 'git_template',
                               bare=True)
             git.Repo.init(self.app.project_dir /
                           ('repos/' + repo.name + '.git'),
                           bare=True,
                           template=self.app.project_dir / 'git_template')
             return Response.redirect(self.app.convert_url('/' + repo.name))
     except Exception as err:
         error = str(err)
         traceback.print_exc(err)
         return Response.render(template, {
             'post': body,
             'error': error,
             'nodes': nodes
         })
     return Response.render(template, {'post': dict(), 'nodes': nodes})
Exemplo n.º 7
0
 def first_create(self, request):
     template = self.view.get_template("create/profile.html")
     error = ""
     if request.method == "POST":
         try:
             form = ProfileForm(request.post())
             prof = Profile()
             prof.name = form["name"]
             prof.ruby = form["ruby"]
             prof.epoch = form["epoch"]
             prof.image = resize(form["image"])
             extra = form["extra"]
             prof.email = form["email"]
             prof.contactOption = int(form["contactOption"])
             prof.contactIdent = form["contactIdent"]
             prof.create()
             for colid, value in extra.items():
                 col = ExtraColumn.retrieve(colid)
                 val = ExtraColumnValue()
                 val.column = col
                 val.profile = prof
                 val.value = value
                 val.create()
             sess = request.session()
             sess["profile_id"] = prof._id
             return Response.redirect(
                 self.app.convert_url("/create/second"))
         except Exception as err:
             error = str(err)
     return Response.render(template, {
         "title": "図鑑登録",
         "error": error,
         "extra_columns": ExtraColumn.list()
     })
Exemplo n.º 8
0
 def delete(self, request):
     template = self.view.get_template("repo/delete.html")
     repo = Repo.retrieve(name=request.params['repo'])
     if (repo.owner != request.user and not InnerPermission.is_accepted(
             'delete_repository', repo.owner.object, request.user)):
         return Response.redirect(self.app.convert_url('/'))
     try:
         if request.method == 'POST':
             if not request.user.password_check(request.post()['password']):
                 raise Exception('wrong password')
             shutil.rmtree(self.app.project_dir /
                           ('repos/' + repo.name + '.git'))
             repo.delete()
             return Response.redirect(self.app.convert_url('/'))
     except Exception as err:
         error = str(err)
         return Response.render(template, {'repo': repo, 'error': error})
     return Response.render(template, {'repo': repo})
Exemplo n.º 9
0
 def process(self, request, handler):
     sess = request.session()
     try:
         if "jwt_token" in sess:
             request.user = User.check_jwt(sess["jwt_token"])
         else:
             return Response.redirect(
                 request.app.project.login_page
                 + "?redirect_to="
                 + urllib.parse.quote(str(request.url), safe="")
             )
     except Exception:
         return Response.redirect(
             request.app.project.login_page
             + "?redirect_to="
             + urllib.parse.quote(str(request.url), safe="")
         )
     return handler(request)
Exemplo n.º 10
0
 def delete(self, request):
     template = self.view.get_template('hook/delete.html')
     repo = Repo.retrieve(name=request.params['repo'])
     if (isinstance(repo.owner.object, Group)
             and not InnerPermission.is_accepted(
                 'update_repository', repo.owner.object, request.user)):
         return Response.redirect(
             self.app.convert_url('/' + request.params['repo'] + '/hook'))
     error = ''
     if request.method == 'POST':
         os.remove(self.app.project_dir / 'repos/{}.git/hooks/{}'.format(
             repo.name, request.params['hook']))
         return Response.redirect(
             self.app.convert_url('/{}/hook'.format(repo.name)))
     return Response.render(template, {
         'repo': repo,
         'name': request.params['hook'],
         'error': error
     })
Exemplo n.º 11
0
 def second_create(self, request):
     template = self.view.get_template("create/tables.html")
     error = ""
     form = {}
     sess = request.session()
     try:
         prof = Profile.retrieve(sess["profile_id"])
     except Exception:
         return Response.redirect(self.app.convert_url("/create"))
     if request.method == "POST":
         form = CareerForm(request.post())
         try:
             careers = form["careers"]
             histories = form["histories"]
             for career_ in careers.values():
                 try:
                     career = Career()
                     career.type = int(career_["type"])
                     career.grade = int(career_["grade"])
                     career.profile = prof
                     career.create()
                 except Exception:
                     pass
             for history_ in histories.values():
                 try:
                     history = TravelHistory()
                     history.year = history_["year"]
                     history.place = history_["place"]
                     history.profile = prof
                     history.description = history_["description"]
                     history.create()
                 except Exception:
                     pass
             return Response.redirect(self.app.convert_url("/create/fin"))
         except Exception as err:
             error = str(err)
     return Response.render(template, {
         "title": "図鑑登録",
         "error": error,
         "form": form
     })
Exemplo n.º 12
0
 def remove_group(self, req):
     try:
         group = Group.retrieve(screen_name=req.params["id"])
         child = Group.retrieve(req.params["gid"])
         group.remove(child)
     except Exception as err:
         print(err)
         pass
     finally:
         return Response.redirect(
             self.app.convert_url("/groups/" + group.screen_name +
                                  "/settings"))
Exemplo n.º 13
0
 def login(self, request):
     template = self.view.get_template("login.html")
     if request.method == "POST":
         try:
             form = LoginForm(request.post())
             result = User.password_auth(form["screen_name"],
                                         form["password"])
             sess = request.session()
             sess["jwt_token"] = result.get_jwt()
             redirect_to = request.query.get("redirect_to", ["/"])[0]
             return Response.redirect(redirect_to)
         except Exception as err:
             return Response.render(template, {"error": err}, status=401)
     return Response.render(template, status=401)
Exemplo n.º 14
0
 def retrieve(self, request):
     template = self.view.get_template('merge/retrieve.html')
     repo = Repo.retrieve(name=request.params['repo'])
     merge = Merge.retrieve(request.params['merge'])
     if request.method == 'POST':
         post = request.post()
         if post['action'] == 'merge':
             merge.merge()
             merge.delete()
         else:
             merge.delete()
         return Response.redirect(self.app.convert_url('/' + repo.name))
     return Response.render(template, {
         "repo": repo,
         "entity": repo.entity,
         "merge": merge
     })
Exemplo n.º 15
0
 def signup(self, request):
     sess = request.session()
     template = self.view.get_template("signup.html")
     invite = UserInvite.retrieve(token=request.query["token"][0])
     if request.method == "POST":
         try:
             form = RegisterForm(request.post())
             user = User()
             user.email = invite.email
             user.set_password(form["password"])
             user.screen_name = form["screen_name"]
             user.name = form["name"]
             user.icon = (resize_icon(form["icon"])
                          if form["icon"] is not None else user.icon)
             user.create()
             sess["jwt_token"] = user.get_jwt()
             roles = invite.roles
             if len(roles) > 0:
                 for role_id in invite.roles.split(":"):
                     role = Role.retrieve(role_id)
                     role.append(user)
             invite.delete()
             return Response.redirect(self.app.convert_url("/"))
         except (ValidationError, ValueError) as err:
             icon = form["icon"]
             return Response.render(
                 template,
                 {
                     "error": err.messsage,
                     "name": form["name"] or invite.name,
                     "screen_name":
                     (form["screen_name"] or invite.screen_name),
                     "password": form["password"] or "",
                     "icon": icon,
                 },
             )
     return Response.render(
         template,
         {
             "icon": invite.icon,
             "name": invite.name or "",
             "screen_name": invite.screen_name or "",
         },
     )
Exemplo n.º 16
0
 def update(self, request):
     template = self.view.get_template("repo/update.html")
     repo = Repo.retrieve(name=request.params['repo'])
     if (repo.owner != request.user and not InnerPermission.is_accepted(
             'update_repository', repo.owner.object, request.user)):
         return Response.redirect(self.app.convert_url('/'))
     try:
         if request.method == 'POST':
             body = request.post()
             name = repo.name
             repo.name = body['name']
             repo.owner = Node(body['owner'])
             repo.update()
             os.rename(
                 self.app.project_dir / ('repos/' + name + '.git'),
                 self.app.project_dir / ('repos/' + repo.name + '.git'))
     except Exception as err:
         error = str(err)
         return Response.render(template, {'repo': repo, 'error': error})
     return Response.render(template, {'repo': repo})
Exemplo n.º 17
0
 def create(self, req):
     template = self.view.get_template("group/create.html")
     groups = Group.list()
     error = ""
     if req.method == "POST":
         try:
             form = GroupCreateForm(req.post())
             group = Group()
             group.name = form["name"]
             group.screen_name = form["screen_name"]
             group.icon = resize_icon(form["icon"])
             group.create()
             if form["parent"] is not None:
                 Group.retrieve(form["parent"]).append(group)
             group.append(req.user)
             return Response.redirect(self.app.convert_url("/groups"))
         except ValidationError as err:
             error = str(err)
     return Response.render(template, {
         "groups": groups,
         "icon": load_noimage_group(),
         "error": error
     })
Exemplo n.º 18
0
 def update_password(self, req):
     template = self.view.get_template("user/update/password.html")
     user = User.retrieve(screen_name=req.params["id"])
     if user._id != req.user._id:
         return Response.redirect(self.app.convert_url("/"))
     error = ""
     if req.method == "POST":
         try:
             form = UserPasswordUpdateForm(req.post())
             if form["password"] != form["password_"]:
                 raise Exception("パスワードが一致しません")
             user.set_password(form["password"])
             user.update()
             error = "パスワードを変更しました"
         except Exception as err:
             error = str(err)
     return Response.render(
         template,
         {
             "user": user,
             "error": error
         },
     )
Exemplo n.º 19
0
 def append(self, req):
     form = req.post()
     try:
         group = Group.retrieve(screen_name=req.params["id"])
         nodes = list()
         if "user" in form:
             for uid in form.getlist("user"):
                 try:
                     nodes.append(User.retrieve(uid))
                 except Exception:
                     pass
         if "group" in form:
             for gid in form.getlist("group"):
                 try:
                     nodes.append(Group.retrieve(gid))
                 except Exception:
                     pass
         group.append_all(nodes)
     except Exception:
         pass
     finally:
         return Response.redirect(
             self.app.convert_url("/groups/" + group.screen_name +
                                  "/settings"))
Exemplo n.º 20
0
    def setup(self, request):
        template = self.view.get_template("setup.html")
        if len(User.list()) > 0:
            return Response.redirect(self.app.convert_url("/login"))
        if request.method == "POST":
            try:
                form = SetupForm(request.post())

                try:
                    owner = Role()
                    owner.name = "Owner"
                    owner.create()
                    manager = Role()
                    manager.name = "Manager"
                    manager.create()
                    normal = Role()
                    normal.name = "Normal"
                    normal.create()
                    inner_owner = InnerRole()
                    inner_owner.name = "Owner"
                    inner_owner.create()
                    inner_manager = InnerRole()
                    inner_manager.name = "Manager"
                    inner_manager.create()
                    inner_normal = InnerRole()
                    inner_normal.name = "Normal"
                    inner_normal.create()
                except Exception:
                    pass

                Permission.accept("admin", owner)
                Permission.accept("create_user", owner)
                Permission.accept("update_user", owner)
                Permission.accept("delete_user", owner)
                Permission.accept("create_group", owner)
                Permission.accept("update_group", owner)
                Permission.accept("delete_group", owner)
                Permission.accept("create_user", manager)
                Permission.accept("update_user", manager)
                Permission.accept("create_group", manager)
                Permission.accept("update_group", manager)

                InnerPermission.accept("admin", inner_owner)
                InnerPermission.accept("add_user", inner_owner)
                InnerPermission.accept("remove_user", inner_owner)
                InnerPermission.accept("add_group", inner_owner)
                InnerPermission.accept("remove_group", inner_owner)
                InnerPermission.accept("add_user", inner_manager)
                InnerPermission.accept("remove_user", inner_owner)
                InnerPermission.accept("add_group", inner_manager)
                InnerPermission.accept("remove_group", inner_owner)

                user = UserInvite()
                user.email = form["email"]
                user.roles = owner._id
                user.create()
                user.mail(
                    "Mitamaへようこそ", "下記リンクから、Mitamaに参加しましょう\n{}".format(
                        self.app.convert_fullurl(request, "/signup?token=" +
                                                 user.token)))

                template = self.view.get_template("confirm.html")
                return Response.render(template)
            except ValidationError as err:
                return Response.render(template, {"error": str(err)})
        return Response.render(template)
Exemplo n.º 21
0
 def logout(self, request):
     sess = request.session()
     sess["jwt_token"] = None
     redirect_to = request.query.get("redirect_to", ["/"])[0]
     return Response.redirect(redirect_to)
Exemplo n.º 22
0
 def cancel(self, req):
     invite = UserInvite.retrieve(req.params["id"])
     invite.delete()
     return Response.redirect(self.app.convert_url("/users/invite"))
Exemplo n.º 23
0
 def process(self, request, handler):
     if User.query.filter(User.password != None).count() == 0:
         return Response.redirect(self.app.convert_url("/setup"))
     else:
         return handler(request)