Пример #1
0
 def post(self):
     self.set_header("Content-Type", "application/json")
     oldPassword = self.get_argument("oldPassword", '')
     newPassword = self.get_argument("newPassword", '')
     newPassword2 = self.get_argument("newPassword2", '')
     if oldPassword and newPassword and newPassword2:
         if newPassword == newPassword2:
             username = self.get_secure_cookie('username')
             old_user = Users.get_by_name_or_email(username)
             oldPassword = md5(
                 oldPassword.encode('utf-8') +
                 old_user.salt.encode('utf-8')).hexdigest()
             if oldPassword == old_user.password:
                 Users.update(username, None, newPassword)
                 user = Users.get(old_user.id)
                 self.set_secure_cookie('userpw',
                                        user.password,
                                        expires_days=1)
                 self.write(escape.json.dumps("OK"))
                 return
             else:
                 self.write(escape.json.dumps("更新用户失败!"))
                 pass
     self.write(escape.json.dumps("请认真填写必填项!"))
     return
Пример #2
0
    def post(self):
        try:
            tf = {'true': 1, 'false': 0}
            act = self.get_argument("act", '').encode('utf-8')
            user_id = self.get_argument("user_id", '').encode('utf-8')
            user_name = self.get_argument("user_name", '').encode('utf-8')
            email = self.get_argument("email", '').encode('utf-8')
            status = tf[self.get_argument("status", 'false').encode('utf-8')]
        except:
            self.write(json.dumps("用户名、邮箱均为必填项!"))
            return

        params = {'user_id': user_id, 'user_name': user_name, 'email': email, 'password': None, 'status': status}
        if act == 'add' and user_name is not None and email is not None:
            password = Users.create(params)
            # sub = {
            #     "%website%": [getAttr("SITE_TITLE").encode('utf-8')],
            #     "%url%": [getAttr("BASE_URL")],
            #     "%name%": [user_name],
            #     "%password%": [password]
            # }
            # sendTemplateEmail(u"密码重置通知 - " + getAttr('SITE_TITLE'), sub, str(email))
            sendEmail(u"密码重置通知 - " + getAttr('SITE_TITLE'), u"您的新密码是:" + password + u"<br /><br />请及时登录并修改密码!",
                      str(email))
        elif act == 'edit' and user_id is not None:
            Users.update(params)

        clear_cache_by_pathlist(['/'])

        self.set_header("Content-Type", "application/json")
        self.write(json.dumps("OK"))
Пример #3
0
  def mark_migrate(self, **kwargs):
    result = {
      'code': 200,
      'message': 'ok'
    }
    author = Users.find(self.request.get('author'))
    user = Users.find(self.request.get('user'))

    options = {}
    options['author'] = author.key
    options['created'] = self.request.get('created')

    [hanasies, _, _], _ = Hanasies.find(options)
    hanasy = hanasies[0] if len(hanasies) > 0 else None

    if hanasy:
      options['created'] = self.request.get('tcreated')
      parts = Parts.find(hanasy.key, options)
      part = parts[0] if len(parts) > 0 else None

      mark, bFound = HanasyBookmarks.find(user.key, hanasy.key)
      mark.position = part.key
      mark.put()

    return self.createRes(200, result)
Пример #4
0
  def like_migrate(self, **kwargs):
    result = {
      'code': 200,
      'message': 'ok'
    }
    author = Users.find(self.request.get('author'))
    user = Users.find(self.request.get('user'))

    options = {}
    options['author'] = author.key
    options['created'] = self.request.get('created')

    [hanasies, _, _], _ = Hanasies.find(options)
    hanasy = hanasies[0] if len(hanasies) > 0 else None

    if hanasy:
      options['created'] = self.request.get('tcreated')
      parts = Parts.find(hanasy.key, options)
      part = parts[0] if len(parts) > 0 else None

      like = Likes(auto_id=True)
      like.user = user.key
      like.target = part.key
      like.put()

    return self.createRes(200, result)
Пример #5
0
def edit_user(id):
    data = data_defaults['user']['edit']
    data['action']['url'] = data['action']['url'] % id
    if request.method == 'GET':
        data['user'] = Users().get_user(id)
        return render_template('user_form.html', data=data)
    if request.method == 'POST':
        _input = g.form.copy()
        _input['id'] = id
        _input['modified_by'] = g.current_user['id']
        u = Users().get_user(id)
        if 'password' in _input and _input['password']:
            _input['password'] = Auth().password_hash(
                _input['confirm_password'])
        else:
            _input['password'] = u['password']
        ok, messages = fswww().validate_user_properties(_input)
        if not ok:
            for m in messages:
                flash(m)
            return render_template('user_form.html', data={'user': _input})
        id = Users().update_user(_input)
        if id is not False:
            url = '/users/edit/%d' % id
            flash('user updated')
            return redirect(url)

        flash('unable to update user')
        return render_template('user_form.html', data={'role': _input})
Пример #6
0
    def get(self):
        act = self.get_argument("act", '').encode('utf-8')
        user_id = self.get_argument("id", '').encode('utf-8')

        obj = None
        if act == 'add':
            obj = Users
            obj.user_id = ''
            obj.user_name = ''
            obj.email = ''
            obj.status = 1
            self.echo('admin_user_edit.html', {
                'title': "添加用户",
                'method': "/admin/users?act=add",
                'obj': obj,
            },
                      layout='_layout_admin.html')
            return
        elif act == 'edit':
            if user_id:
                obj = Users.get(user_id)
                self.echo('admin_user_edit.html', {
                    'title': "编辑用户",
                    'method': "/admin/users?act=edit",
                    'obj': obj,
                },
                          layout='_layout_admin.html')
                return
        elif act == 'del':
            if user_id:
                Users.delete(user_id)
                clear_cache_by_pathlist(['/'])
            self.set_header("Content-Type", "application/json")
            self.write(json.dumps("OK"))
            return

        # 用户列表
        page = self.get_argument("page", 1)
        category = Users.get_paged(page, getAttr('ADMIN_USER_NUM'))
        total = math.ceil(Users.count_all() / float(getAttr('ADMIN_USER_NUM')))
        if page == 1:
            self.echo('admin_user_list.html', {
                'title': "用户列表",
                'objs': category,
                'obj': obj,
                'total': total,
            },
                      layout='_layout_admin.html')
        else:
            result = {
                'list': category,
                'total': total,
            }
            self.set_header("Content-Type", "application/json")
            self.write(json.dumps(result, default=dthandler))
            return
Пример #7
0
    def get(self):
        act = self.get_argument("act", '').encode('utf-8')
        user_id = self.get_argument("id", '').encode('utf-8')

        obj = None
        if act == 'add':
            obj = Users
            obj.user_id = ''
            obj.user_name = ''
            obj.email = ''
            obj.status = 1
            self.echo('admin_user_edit.html', {
                'title': "添加用户",
                'method': "/admin/users?act=add",
                'obj': obj,
            }, layout='_layout_admin.html')
            return
        elif act == 'edit':
            if user_id:
                obj = Users.get(user_id)
                self.echo('admin_user_edit.html', {
                    'title': "编辑用户",
                    'method': "/admin/users?act=edit",
                    'obj': obj,
                }, layout='_layout_admin.html')
                return
        elif act == 'del':
            if user_id:
                Users.delete(user_id)
                clear_cache_by_pathlist(['/'])
            self.set_header("Content-Type", "application/json")
            self.write(json.dumps("OK"))
            return

        # 用户列表
        page = self.get_argument("page", 1)
        category = Users.get_paged(page, getAttr('ADMIN_USER_NUM'))
        total = math.ceil(Users.count_all() / float(getAttr('ADMIN_USER_NUM')))
        if page == 1:
            self.echo('admin_user_list.html', {
                'title': "用户列表",
                'objs': category,
                'obj': obj,
                'total': total,
            }, layout='_layout_admin.html')
        else:
            result = {
                'list': category,
                'total': total,
            }
            self.set_header("Content-Type", "application/json")
            self.write(json.dumps(result, default=dthandler))
            return
Пример #8
0
def test_edit_first_user_name(app):
    if app.users.count() == 0:
        app.users.create(Users(firstname="testuser"))
    old_users = app.users.get_users_list()
    index = randrange(len(old_users))
    user = Users(firstname="New user", lastname=None)
    user.id = old_users[index].id
    app.users.edit_user_by_index(index, user)
    new_users = app.users.get_users_list()
    assert len(old_users) == len(new_users)
    old_users[index] = user
    assert sorted(old_users, key=Users.id_or_max) != sorted(
        new_users, key=Users.id_or_max)
Пример #9
0
def validate_account(form, db):
    email = form.email.data
    tmp_password = form.password.data
    username = form.username.data
    # randomly generate an 8 character permalink it should be unique
    # create a random sequence of length 16. A mix of letters and digits.
    permalink = ""
    for x in range(16):
        if random.randint(0, 11) <= 5:
            permalink = permalink + random.choice(string.ascii_letters)
        else:
            permalink = permalink + random.choice(string.digits)
    # Add a check to see if permalink is in database and loop until we create a permalink that is not
    # hash the password before storing it inside the database for security concerns
    password = bcrypt.hashpw(tmp_password.encode('utf8'), salt=bcrypt_salt).decode('utf8')
    my_user = Users(email=email, password=password, username=username, permalink=permalink)
    # check if checkpw works
    print(bcrypt.checkpw(tmp_password.encode('utf8'), password.encode('utf8')))
    db.session.add(my_user)
    try:
        db.session.commit()
        return True
    except IntegrityError:
        # cancel all changes
        db.session.rollback()
        return False
Пример #10
0
def delete_user_from_group(app):
    new_group = db.get_group_list()
    group = random.choice(new_group)
    if len(db.get_users_list()) == 0:
        app.users.create(
            Users(firstname="somebody",
                  lastname="someone",
                  email="*****@*****.**",
                  homephone=12345,
                  workphone=123456,
                  mobilephone=1234567,
                  address="somewhere"))
    elif len(db.get_group_list()) == 0:
        app.create(Group(name="New group for user"))
    elif len(db.get_users_in_group(group)) == 0:
        app.add_user_to_group()
    else:
        ui_list = db.get_users_in_group(group)
        random_user = random.choice(ui_list)
        app.users.delete_user_from_group()
        db_list = db.get_users_in_group(group)
        ui_list.remove(random_user)
        assert sorted(ui_list,
                      key=Group.id_or_max) == sorted(db_list,
                                                     key=Group.id_or_max)
Пример #11
0
 def delete(self, **kwargs):
   result = {
     'code': 400,
     'message': 'bad request'
   }
   
   # check user validation
   if self.get_user() is None:
     result['code'] = 401
     result['message'] = 'unauthorized'
     return self.createRes(401, result)
   
   uid = int(kwargs.get('uid'))
   if uid != self.get_user().get('uid'):
     result['code'] = 401
     result['message'] = 'unauthorized'
     return self.createRes(401, result)
   
   # get user info
   user = Users.get(id=uid)
   connections = Connections.find(user.key)
   
   # delete connection info
   for connection in connections:
     connection.key.delete()
   
   # delete user info
   user.key.delete()
   self.session.clear()
   
   result['code'] = 200
   result['message'] = 'OK'
   return self.createRes(200, result)
Пример #12
0
def do_login(request):
    params = request.get_json()
    mail = params['mail']
    password = params['user_password']
    user = Users.confirm_account(mail, password)
    print(user)
    return json.dumps({'result': user is not None, 'user': user})
Пример #13
0
  def post(self, **kwargs):
    result = {
      'code'    : 400,
      'message' : 'bad request'
    }
    
    uid = self.get_user().get('uid') if self.get_user() else None
    if uid is None:
      result['code'] = 401
      result['message'] = 'not authorized'
      return self.createRes(401, result)
    
    if self.arguments.get('type') in ['notice', 'faq'] and self.get_user().get('admin') is None:
      result['code'] = 401
      result['message'] = 'not authorized'
      return self.createRes(401, result)

    owner = Users.get(id=self.get_user().get('uid'))
    board = Boards(auto_id=True)
    for item in self.arguments:
      setattr(board, item, self.arguments.get(item))
    
    board.service = kwargs.get('service')
    board.owner = owner.key
    board.put()

    result['code'] = 200
    result['Board'] = board.to_obj()
    result['message'] = 'OK'

    return self.createRes(result['code'], result)
def test_add_user_to_group(app):
    if len(db.get_users_list()) == 0:
        app.users.create(
            Users(firstname="somebody",
                  lastname="someone",
                  email="*****@*****.**",
                  homephone=12345,
                  workphone=123456,
                  mobilephone=1234567,
                  address="somewhere"))
    elif len(db.get_group_list()) == 0:
        app.group.create(Group(name="New group for user"))
    else:
        old_user = db.get_users_list()
        old_group = db.get_group_list()
        if old_group:
            new_group = db.get_group_list()
            group = random.choice(new_group)
            group_id = group.id
            if old_user:
                new_user = db.get_users_not_in_group(group)
                random_user = random.choice(new_user)
                id = random_user.id
                ui_list = db.get_users_in_group(group)
                app.users.add_user_to_group(id, group_id)
                db_list = db.get_users_in_group(group)
                ui_list.append(random_user)
                assert sorted(ui_list, key=Group.id_or_max) == sorted(
                    db_list, key=Group.id_or_max)
 def login(self, form):
     u, p = form.get('username'), form.get('password')
     user = Users().get_by_username(u)
     print repr(user)
     if not user or not Auth().authorize_user(user, p):
         return False
     return user
Пример #16
0
 def isAuthor(self):
     #user_name_cookie = self.get_secure_cookie('username', '')
     email_cookie = self.get_secure_cookie('email', '')
     password_cookie = self.get_secure_cookie('password', '')
     from model.users import Users
     return Users.check_user_or_email_password(email_cookie,
                                               password_cookie)
Пример #17
0
    def post(self):
        self.set_header("Content-Type", "application/json")
        try:
            user_name = self.get_argument("name")
            email = self.get_argument("email")
            captcha = self.get_argument("captcha", "")
        except:
            self.write(json.dumps("用户名、邮箱、验证码均为必填项!"))
            return

        if captcha:
            if self.get_secure_cookie("captcha") != captcha:
                self.write(json.dumps("验证码填写错误!"))
                return
        else:
            user_name_cookie = self.get_secure_cookie('username')
            user_pw_cookie = self.get_secure_cookie('userpw')
            if not Users.check_user_or_email_password(user_name_cookie,
                                                      user_pw_cookie):
                self.write(json.dumps("重置密码失败!"))
                return

        if user_name and email and Users.check_name_email(user_name, email):
            password = random_string(16)
            params = {
                'user_name': user_name,
                'email': email,
                'password': password
            }
            Users.update(params)
            # sub = {
            #     "%website%": [getAttr("SITE_TITLE").encode('utf-8')],
            #     "%url%": [getAttr("BASE_URL")],
            #     "%name%": [user_name],
            #     "%password%": [password]
            # }
            #sendTemplateEmail(u"密码重置通知 - " + getAttr('SITE_TITLE'), sub, str(email))
            sendEmail(u"密码重置通知 - " + getAttr('SITE_TITLE'),
                      u"您的新密码是:" + password + u"<br /><br />请及时登录并修改密码!",
                      str(email))

            self.write(json.dumps("OK"))
            return
        else:
            self.write(json.dumps("重置密码失败!"))
            return
Пример #18
0
def create_user(request):
    params = request.get_json()
    name = params['name']
    email = params['email']
    password = params['password']
    position = params['position']

    if (name is not None) and (email is not None):
        get_email_ = Users.find_email(email)
        if get_email_ is not None:
            return json.dumps({'result': False, 'mess': 'email is exited'})
        else:
            if Users.create_user(password, name, email, position):
                return json.dumps({'result': True})
            else:
                return json.dumps({'result': False, 'mess': 'can not create user'})
    return json.dumps({'result': False, 'mess': 'Write Information'})
Пример #19
0
def edit_user(request):
    params = request.get_json()
    user_id = params['user_id']
    password = params['password']
    name = params['name']
    email = params['email']
    result = Users.edit_user(user_id, email, password, name)
    return json.dumps({'result': True}) if result else json.dumps({'result': False})
Пример #20
0
def addContact():
    '''
    Add a contact
    {
      "sender_id": "4",
      "displayName": "Mohit",
      "phoneNum": "8427434777",
      "countryPhoneCode":"91"  
    }
    '''
    auth_header = request.headers.get('Authorization')
    sub = jwtUtil.parse_decode_auth_token(auth_header, SECRETKEY)

    req_json = request.get_json()
    returnStatus = {"status": "SUCCESS"}
    session = Session()
    try:
        contactJson = req_json['contact']
        sender_id = contactJson['sender_id']
        sender_name = contactJson['sender_name']
        con_displayName = contactJson['display_name']
        con_phone_Num = contactJson['phone_number']
        country_phone_code = contactJson['country_phone_code']

        if (sender_name == sub):
            contact = Users(display_name=con_displayName,
                            phone_number=con_phone_Num,
                            country_code=country_phone_code,
                            contact_id=sender_id)
            session.add(contact)
            session.commit()
            session.refresh(contact)
            #         schema = UserSchema(many = True)
            #         contactList = schema.dump(contact)
            returnStatus.update({
                "user_id":
                contact.user_id,
                "display_name":
                contact.display_name,
                "phone_number":
                contact.phone_number,
                "country_phone_code":
                contact.country_phone_code
            })
            print(contact.user_id)
        else:
            returnStatus = {"status": "FAILURE"}
    except Exception as e:
        print(e)
        returnStatus = {
            "status":
            "Some problem while adding contact, please check for duplicity"
        }
    finally:
        #returnStatus = "Contact {0} added success fully".format(contact.user_id)
        session.close()
    return json.dumps(returnStatus)
Пример #21
0
 def get_users_from_view_page(self, index):
     wd = self.app.wd
     self.open_users_view_by_index(index)
     text = wd.find_element_by_id("content").text
     homephone = re.search("H: (.*)", text).group(1)
     workphone = re.search("W: (.*)", text).group(1)
     mobilephone = re.search("M: (.*)", text).group(1)
     secondaryphone = re.search("P: (.*)", text).group(1)
     return Users(homephone=homephone, workphone=workphone, mobilephone=mobilephone, secondaryphone=secondaryphone)
def edit_user(request):
    params = request.get_json()
    user_id = params['user_id']
    password = params['user_password']
    name = params['user_name']
    mail = params['mail']
    position = params['position']
    result = Users.edit_user(user_id, mail, password, name, position)
    return json.dumps({'result': True}) if result else json.dumps(
        {'result': False})
Пример #23
0
 def post(self):
     self.set_header("Content-Type", "application/json")
     oldPassword = self.get_argument("oldPassword", '')
     newPassword = self.get_argument("newPassword", '')
     newPassword2 = self.get_argument("newPassword2", '')
     if oldPassword and newPassword and newPassword2:
         if newPassword == newPassword2:
             username = self.get_secure_cookie('username')
             old_user = Users.get_by_name_or_email(username)
             oldPassword = md5(oldPassword.encode('utf-8') + old_user.salt.encode('utf-8')).hexdigest()
             if oldPassword == old_user.password:
                 Users.update(username, None, newPassword)
                 user = Users.get(old_user.id)
                 self.set_secure_cookie('userpw', user.password, expires_days=1)
                 self.write(escape.json.dumps("OK"))
                 return
             else:
                 self.write(escape.json.dumps("更新用户失败!"))
                 pass
     self.write(escape.json.dumps("请认真填写必填项!"))
     return
Пример #24
0
  def migrate(self, **kwargs):
    result = {
      'code': 400,
      'message': 'bad request'
    }

    options = {}
    author_email = self.request.get('author')
    hanasy_created = self.request.get('screated')
    pid = 0
    author_info = Users.find(author_email)
    author = author_info.key.get()

    options['author'] = author_info.key
    options['created'] = hanasy_created

    [hanasies, _, _], _ = Hanasies.find(options)
    hanasy = hanasies[0]

    if type(hanasy) == ndb.key.Key:
      result['code'] = 404
      result['message'] = 'not found'
      return self.createRes(404, result)

    if not pid:
      # post new part
      arguments = self.arguments
      args_require = ['content', 'imageUrl', 'image', 'videoUrl']

      # check parameter validation
      if len(set(arguments) & set(args_require)) == 0:
        result['code'] = 400
        result['message'] = 'bad request'
        return self.createRes(400, result)

      part = Parts(auto_id=True, parent=hanasy.key)
      part.set(self.convertRequsetParameter(self.arguments, ['author','screated']))

      hanasy.updated = datetime.datetime.now()
      hanasy.partCount = int(hanasy.partCount if hanasy.partCount else 0) + 1
      hanasy.status = 'onair'
      hanasy.put()

      if part:
        result['code'] = 201
        result['message'] = 'OK'
        result['Part'] = part.to_obj()
        return self.createRes(201, result)
      else:
        result['code'] = 400
        result['message'] = 'already exists'
        return self.createRes(400, result)
Пример #25
0
    def post(self):
        self.set_header("Content-Type", "application/json")
        try:
            user_name = self.get_argument("name")
            email = self.get_argument("email")
            captcha = self.get_argument("captcha", "")
        except:
            self.write(json.dumps("用户名、邮箱、验证码均为必填项!"))
            return

        if captcha:
            if self.get_secure_cookie("captcha") != captcha:
                self.write(json.dumps("验证码填写错误!"))
                return
        else:
            user_name_cookie = self.get_secure_cookie('username')
            user_pw_cookie = self.get_secure_cookie('userpw')
            if not Users.check_user_or_email_password(user_name_cookie, user_pw_cookie):
                self.write(json.dumps("重置密码失败!"))
                return

        if user_name and email and Users.check_name_email(user_name, email):
            password = random_string(16)
            params = {'user_name': user_name, 'email': email, 'password': password}
            Users.update(params)
            # sub = {
            #     "%website%": [getAttr("SITE_TITLE").encode('utf-8')],
            #     "%url%": [getAttr("BASE_URL")],
            #     "%name%": [user_name],
            #     "%password%": [password]
            # }
            #sendTemplateEmail(u"密码重置通知 - " + getAttr('SITE_TITLE'), sub, str(email))
            sendEmail(u"密码重置通知 - " + getAttr('SITE_TITLE'), u"您的新密码是:" + password + u"<br /><br />请及时登录并修改密码!", str(email))

            self.write(json.dumps("OK"))
            return
        else:
            self.write(json.dumps("重置密码失败!"))
            return
Пример #26
0
def test_delete_some_user(app, db, check_ui):
    if len(db.get_users_list()) == 0:
        app.users.create(Users(firstname="testuser"))
    old_users = db.get_users_list()
    user = random.choice(old_users)
    app.users.delete_user_by_id(user.id)
    new_users = db.get_users_list()
    assert len(old_users) - 1 == len(new_users)
    old_users.remove(user)
    assert old_users == new_users
    if check_ui:
        assert sorted(new_users, key=Users.id_or_max) == sorted(
            app.group.get_users_list(), key=Users.id_or_max)
Пример #27
0
    def post(self):
        try:
            tf = {'true': 1, 'false': 0}
            act = self.get_argument("act", '').encode('utf-8')
            user_id = self.get_argument("user_id", '').encode('utf-8')
            user_name = self.get_argument("user_name", '').encode('utf-8')
            email = self.get_argument("email", '').encode('utf-8')
            status = tf[self.get_argument("status", 'false').encode('utf-8')]
        except:
            self.write(json.dumps("用户名、邮箱均为必填项!"))
            return

        params = {
            'user_id': user_id,
            'user_name': user_name,
            'email': email,
            'password': None,
            'status': status
        }
        if act == 'add' and user_name is not None and email is not None:
            password = Users.create(params)
            # sub = {
            #     "%website%": [getAttr("SITE_TITLE").encode('utf-8')],
            #     "%url%": [getAttr("BASE_URL")],
            #     "%name%": [user_name],
            #     "%password%": [password]
            # }
            # sendTemplateEmail(u"密码重置通知 - " + getAttr('SITE_TITLE'), sub, str(email))
            sendEmail(u"密码重置通知 - " + getAttr('SITE_TITLE'),
                      u"您的新密码是:" + password + u"<br /><br />请及时登录并修改密码!",
                      str(email))
        elif act == 'edit' and user_id is not None:
            Users.update(params)

        clear_cache_by_pathlist(['/'])

        self.set_header("Content-Type", "application/json")
        self.write(json.dumps("OK"))
Пример #28
0
  def deactivate(self, **kwargs):
    result = {
      'code': 400,
      'message': 'bad request'
    }

    if self.get_user() is None:
      result['code'] = 401
      result['message'] = 'unauthorized'

    elif self.get_user().get('uid') != int(kwargs.get('uid')):
      result['code'] = 401
      result['message'] = 'unauthorized'

    else:
      # get user info
      user = Users.get(id=self.get_user().get('uid'))
      connections = Connections.find(user.key)

      # delete connection info
      for connection in connections:
        connection.key.delete()

      # delete user info
      user.key.delete()
      self.session.clear()

      result['code'] = 200
      result['message'] = 'OK'

    if result['code'] == 200:
      if self.arguments.get('returnTo', None):
        return self.redirect(str(self.arguments.get('returnTo')))
      else:
        result['code'] = 200
        result['message'] = 'OK'
        return self.createRes(200, result)
    else:
      if self.arguments.get('returnTo', None):
        options = {
          'returnTo': self.arguments.get('returnTo'),
          'message': result['message']
        };

        if self.get_user():
          options['uid'] = self.get_user().get('uid')
        template = JINJA_ENVIRONMENT.get_template(self.arguments.get('dialog'))
        return self.response.write(template.render(options))
      else:
        return self.createRes(401, result)
Пример #29
0
 def get_users_list(self):
     list = []
     cursor = self.connection.cursor()
     try:
         cursor.execute(
             "select id, firstname, lastname from addressbook where deprecated='0000-00-00 00:00:00'"
         )
         for row in cursor:
             (id, firstname, lastname) = row
             list.append(
                 Users(id=str(id), firstname=firstname, lastname=lastname))
     finally:
         cursor.close()
     return list
Пример #30
0
 def get_users_info_from_edit_page(self, index):
     wd = self.app.wd
     self.open_users_to_edit_by_index(index)
     firstname = wd.find_element_by_name("firstname").get_attribute("value")
     lastname = wd.find_element_by_name("lastname").get_attribute("value")
     id = wd.find_element_by_name("id").get_attribute("value")
     homephone = wd.find_element_by_name("home").get_attribute("value")
     workphone = wd.find_element_by_name("work").get_attribute("value")
     mobilephone = wd.find_element_by_name("mobile").get_attribute("value")
     secondaryphone = wd.find_element_by_name("phone2").get_attribute("value")
     address = wd.find_element_by_name("address").text
     email = wd.find_element_by_name("email").get_attribute("value")
     email2 = wd.find_element_by_name("email2").get_attribute("value")
     email3 = wd.find_element_by_name("email3").get_attribute("value")
     return Users(firstname=firstname,lastname=lastname, id=id, homephone=homephone, workphone=workphone,address=address,
                  mobilephone=mobilephone, secondaryphone=secondaryphone, email=email, email2=email2, email3=email3)
Пример #31
0
 def get_users_list(self):
     if self.user_cache is None:
         wd = self.app.wd
         self.open_webpage()
         self.user_cache = []
         for row in wd.find_elements_by_name("entry"):
             cells = row.find_elements_by_tag_name("td")
             firstname = cells[2].text
             lastname = cells[1].text
             id = cells[0].find_element_by_tag_name("input").get_attribute("value")
             address = cells[3].text
             all_phones = cells[5].text
             all_emails = cells[4].text
             self.user_cache.append(Users(firstname=firstname, lastname=lastname, id=id, address=address,
                                          all_phones_from_home_page=all_phones, all_emails_from_home_page=all_emails))
     return list(self.user_cache)
Пример #32
0
 def get_user_info_by_id(self, id):
     wd = self.app.wd
     self.app.open_home_page()
     row = wd.find_element_by_xpath('//td/*[@id="' + id + '"]/../..')
     cells = row.find_elements_by_tag_name("td")
     id = cells[0].find_element_by_tag_name("input").get_attribute("value")
     firstname = cells[2].text
     lastname = cells[1].text
     address = cells[3].text
     all_emails = cells[4].text
     all_phones = cells[5].text
     return Users(id=id,
                  firstname=firstname,
                  lastname=lastname,
                  address=address,
                  all_emails_from_home_page=all_emails,
                  all_phones_from_home_page=all_phones)
Пример #33
0
def signup():
    """
        curl -d '{"name":"greenbear", "id":"greenbear", "passwd": "greenbear"}' -H "Content-Type: application/json" -X POST http://localhost:5000/users/signup
        - 만약, create_user가 있다면 singup으로 redirect => 신규 id 생성으로 요청
        - 그렇지 않다면, user 생성 후, login 페이지로 redirect
        :return:
        """

    logger_info(f"[{request.remote_addr}] {request.method}")
    if request.method == "POST":
        logger_info(f"request.json: {request.json}")
        logger_info(f"request.form: {request.form}")
        if request.json:
            if not request.json or not 'id' in request.json:
                logger_info(f"400 error : {request}")
                abort(400)
                logger_info(f"request params: {request.json}")

        with session_scope() as db_session:
            if request.json:
                user_id = request.json.get('id')
                user_name = request.json.get('name')
                user_pw = request.json.get('pw')
            else:
                user_id = request.form.get('id')
                user_name = request.form.get('name')
                user_pw = request.form.get('pw')
            user = db_session.query(Users).filter_by(id=user_id).first()
            if user:
                # 만약 기존 user가 있다면, 신규 ID로 user를 생성할 수 있도록 다시 redirect
                logger_info(
                    f"{user._asdict()} is already. try signup with new_user")
                flash("user id already exists.")
                return redirect(url_for('users.signup'))

            user_pw = (bcrypt.hashpw(user_pw.encode('UTF-8'),
                                     bcrypt.gensalt())).decode('utf-8')
            cret_dt = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            new_user = Users(user_id, user_name, user_pw, cret_dt)
            db_session.add(new_user)
            logger_info(f"create new_user: {new_user.id}")
            return redirect(url_for('users.login'))
    elif request.method == "GET":
        return render_template("signup_form.html")
Пример #34
0
  def get(self, **kwargs):
    result = {
      'code'    : 400,
      'message' : 'bad request'
    }

    service = kwargs.get('service')
    type = kwargs.get('type')
    category = self.arguments.get('category')
    owner = None
    if type == 'qna' and self.get_user():
      owner = Users.get(id=self.get_user().get('uid')).key

    result['Boards'] = self.listToObject(Boards.find(service, type, category, owner=owner))
    result['code'] = 200
    result['message'] = 'OK'

    return self.createRes(result['code'], result)
Пример #35
0
  def migrate(self, **kwargs):
    result = {
      'code': 400,
      'message': 'bad request'
    }

    author_email = self.request.get('author')
    hid = 0
    author_info = Users.find(author_email)
    author = author_info.key.get()

    if type(author) == ndb.key.Key:
      result['code'] = 401
      result['message'] = 'not allowed'
      return self.createRes(401, result)

    if not hid:
      # post new hanasy
      arguments = self.arguments
      args_require = ['title', 'description']

      # check parameter validation
      if len(set(arguments) & set(args_require)) != len(args_require):
        result['code'] = 400
        result['message'] = 'bad request'
        return self.createRes(400, result)

      hanasy = Hanasies(auto_id=True, parent=author.key)

      if 'tokCount' in self.arguments:
        self.arguments['partCount'] = self.arguments['tokCount']
        del self.arguments['tokCount']

      hanasy.set(self.convertRequsetParameter(self.arguments, ['author', 'author_id']))

      if hanasy:
        result['code'] = 201
        result['message'] = 'OK'
        result['Hanasee'] = hanasy.to_obj()
        return self.createRes(201, result)
      else:
        result['code'] = 500
        result['message'] = 'failed'
        return self.createRes(500, result)
Пример #36
0
def register():
    '''
    Add a User
    {
      
      "display_name": "Mohit",
      "phone_number": "8427434777",
      "country_phone_code":"91",
      callback_url : "hdjkfhkdjsf",
      telesign_customer_id : "ghdkjafhjd",
      telesign_api_key : "jsdhfjkhsdfkj",
      password : "******"
          }
    '''
    req_json = request.get_json()
    returnStatus = "status: User created successfully"
    session = Session()
    try:
        userJson = req_json['contact']
        user_displayName = userJson['display_name']
        phone_Num = userJson['phone_number']
        country_phone_code = userJson['country_phone_code']
        callback_url = userJson['callback_url']
        telesign_customer_id = userJson['telesign_customer_id']
        telesign_api_key = userJson['telesign_api_key']
        password = userJson['password']

        newUser = Users(display_name=user_displayName,
                        phone_number=phone_Num,
                        country_code=country_phone_code,
                        callback_url=callback_url,
                        ts_cust_id=telesign_customer_id,
                        ts_api_key=telesign_api_key,
                        password=password)
        session.add(newUser)
        session.commit()
    except Exception as e:
        print(e)
        returnStatus = "status: Some problem while registering user, please check for duplicity"
    finally:
        returnStatus = "status: Registration successfull"
        #returnStatus = "Contact {0} added success fully".format(contact.user_id)
        session.close()
    return json.dumps(returnStatus)
Пример #37
0
  def devices(self, **kwargs):
    result = {
      'code': 400,
      'message': 'bad request'
    }

    device_args = ['deviceId', 'appName', 'regId']
    # check parameter validation
    if len(set(self.arguments) & set(device_args)) != len(device_args):
      result['code'] = 400
      result['message'] = 'bad request'
      return self.createRes(400, result)

    if 'deviceInfo' not in self.session:
      self.session['deviceInfo'] = {}

    self.session['deviceInfo'] = {
      'deviceId': self.arguments.get('deviceId'),
      'appName': self.arguments.get('appName'),
      'regId': self.arguments.get('regId')
    }

    device_key = ndb.Key('Devices', '%s|%s' % (self.arguments.get('appName'), self.arguments.get('deviceId')))
    device = device_key.get()

    if device is None:
      device = Devices(key=device_key)
      device.regId = self.arguments.get('regId')
      device.appName = self.arguments.get('appName')
      device.deviceId = self.arguments.get('deviceId')

    elif device.regId != self.arguments.get('regId'):
      device.regId = self.arguments.get('regId')

    if self.get_user():
      user = Users.get(id=self.get_user().get('uid'))
      device.user = user.key
      result['User'] = user.to_obj(mine=True)

    device.put()
    result['code'] = 200
    return self.createRes(200, result)
Пример #38
0
def create_user():
    data = data_defaults['user']['create']
    if request.method == 'GET':
        return render_template('user_form.html', data=data)
    if request.method == 'POST':
        _input = g.form.copy()
        _input['modified_by'] = g.current_user['id']
        ok, messages = fswww().validate_user_properties(_input)
        if not ok:
            for m in messages:
                flash(m)
            return render_template('user_form.html', data={'user': _input})
        id = Users().create_user(_input)
        if id is not False:
            url = '/user/edit/%d' % id
            flash('user created')
            return redirect(url)

        flash('unable to create user')
        return render_template('user_form.html', data={'user': _input})
Пример #39
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if Users.confirm_account(username, password):
            res = {'result': 'True'}
            return json.dumps(res)

        else:
            res = {'result': 'False', 'error': 'user or password error'}
            return json.dumps(res)

    else:
        return Response('''
            <form action="" method="post">
                <p><input type=text name=username>
                <p><input type=password name=password>
                <p><input type=submit value=Login>
            </form> 
            ''')
Пример #40
0
def test_delete_some_user(app, db, check_ui):
    if len(db.get_users_list()) == 0:
        app.users.create(
            Users(firstname="somebody",
                  lastname="someone",
                  email="*****@*****.**",
                  homephone=12345,
                  workphone=123456,
                  mobilephone=1234567,
                  address="somewhere"))
    old_users = db.get_users_list()
    user = random.choice(old_users)
    app.users.delete_user_by_id(user.id)
    new_users = db.get_users_list()
    assert len(old_users) - 1 == len(new_users)
    old_users.remove(user)
    assert old_users == new_users
    if check_ui:
        assert sorted(new_users, key=Users.id_or_max) == sorted(
            app.group.get_users_list(), key=Users.id_or_max)
Пример #41
0
        def authorized_handler(self, *args, **kw):
            request = self.request
            #username_cookie = self.get_secure_cookie('username')
            #userid_cookie = self.get_secure_cookie('user_id')
            email_cookie = self.get_secure_cookie('email')
            password_cookie = self.get_secure_cookie('password')
            from model.users import Users

            user = Users.check_user_or_email_password(email_cookie, password_cookie)

            if request.method == 'GET':
                if not user:
                    self.redirect(url)
                    return False
                else:
                    handler(self, *args, **kw)
            else:
                if not user:
                    self.error(403)
                else:
                    handler(self, *args, **kw)
Пример #42
0
        def authorized_handler(self, *args, **kw):
            request = self.request
            #username_cookie = self.get_secure_cookie('username')
            #userid_cookie = self.get_secure_cookie('user_id')
            email_cookie = self.get_secure_cookie('email')
            password_cookie = self.get_secure_cookie('password')
            from model.users import Users

            user = Users.check_user_or_email_password(email_cookie,
                                                      password_cookie)

            if request.method == 'GET':
                if not user:
                    self.redirect(url)
                    return False
                else:
                    handler(self, *args, **kw)
            else:
                if not user:
                    self.error(403)
                else:
                    handler(self, *args, **kw)
Пример #43
0
  def action(self, **kwargs):
    result = {
      'code': 400,
      'message': 'bad request'
    }

    cid = int(kwargs.get('cid', 0))
    url = kwargs.get('url')
    action = kwargs.get('action')

    if not self.get_user():
      result['code'] = 401
      result['message'] = 'not allowed'
      return self.createRes(401, result)

    user = Users.get(id=self.get_user().get('uid'))
    comment = Comments.get(id=cid)

    if action in ['like', 'unlike']:
      like = Likes.find(ndb.Key(Users, self.get_user().get('uid')), [comment.key])
      if len(like) > 0 and action == 'unlike':
        like[0].key.delete()
      elif len(like) == 0 and action == 'like':
        like = Likes(auto_id=True)
        like.user = user.key
        like.target = comment.key
        like.put()
      else:
        result['code'] = 500
        result['message'] = 'internal error'
        return self.createRes(500, result)

      comment.likeCount = int(comment.likeCount if comment.likeCount else 0) + (1 if action == 'like' else -1)
      comment.put()

      result['code'] = 200
      result['message'] = 'OK'
      result['Comment'] = comment.to_obj()
      return self.createRes(200, result)
Пример #44
0
    def post(self):
        self.set_header("Content-Type", "application/json")

        try:
            name_or_email = self.get_argument("name_or_email").encode('utf-8')
            password = self.get_argument("password").encode('utf-8')
            captcha = self.get_argument("captcha").encode('utf-8')
        except:
            self.write(json.dumps("用户名、密码、验证码均为必填项!"))
            return

        if self.get_secure_cookie("captcha") != captcha:
            self.write(json.dumps("验证码填写错误或用户不存在!"))
            return

        has_user = Users.get_by_name_or_email(name_or_email)
        if has_user and has_user.status == 1 and has_user.deleted == 0:
            password += has_user.salt
            password = md5(password.encode('utf-8')).hexdigest()
            if password == has_user.password:
                self.set_secure_cookie('username',
                                       has_user.user_name,
                                       expires_days=365)
                self.set_secure_cookie('user_id',
                                       str(has_user.user_id),
                                       expires_days=365)
                self.set_secure_cookie('email',
                                       has_user.email,
                                       expires_days=365)
                self.set_secure_cookie('password', password, expires_days=365)
                self.write(json.dumps("OK"))
                return
            else:
                self.write(json.dumps("权限验证失败或帐户不可用!"))
                return
        else:
            self.write(json.dumps("验证码填写错误或用户不存在!"))
            return
Пример #45
0
  def devices_migrate(self, **kwargs):
    result = {
      'code': 400,
      'message': 'bad request'
    }
    author = None
    if self.request.get('author', None):
      author = Users.find(self.request.get('author')).key

    arguments = self.request.arguments()
    device_args = ['deviceId', 'appName', 'regId']

    # check parameter validation
    if len(set(arguments) & set(device_args)) != len(device_args):
      result['code'] = 400
      result['message'] = 'bad request'
      return self.createRes(400, result)

    device, bCreated = Devices.get(self.request.get('appName'), self.request.get('deviceId'))
    if not bCreated:
      device.regId = self.request.get('regId')
      if author:
        device.user = author
      device.put()
Пример #46
0
  def regist(self, **kwargs):
    result = {
      'code': 400,
      'message': 'bad request'
    }

    # check arguments
    if not (self.arguments.get('email') and self.arguments.get('password') and self.arguments.get('nickname')):
      result['code'] = 400
      result['message'] = 'bad request'
      return self.createRes(400, result)

    else:
      user, created = Users.regist(self.arguments.get('email'), self.arguments)
      if not created:
        result['code'] = 400
        result['message'] = 'already exists'
        return self.createRes(400, result)

      else:
        result['code'] = 201
        result['message'] = 'OK'
        result['User'] = user.to_obj(mine=True)
        return self.createRes(201, result)
Пример #47
0
 def convert(user):
     return Users(id=str(user.id), firstname=user.firstname, lastname=user.lastname, email=user.email)
Пример #48
0
    except AttributeError, e1:
      result['code'] = 400
      result['message'] = 'bad request'
      return self.createRes(401, result)

    if not self.get_user():
      result['code'] = 401
      result['message'] = 'not allowed'
      return self.createRes(401, result)

    if uid and (uid != self.get_user().get('uid')):
      result['code'] = 401
      result['message'] = 'not allowed'
      return self.createRes(401, result)

    author = Users.get(id=uid)
    if type(author) == ndb.key.Key:
      result['code'] = 401
      result['message'] = 'not allowed'
      return self.createRes(401, result)

    if not hid:
      # post new hanasy
      arguments = self.arguments
      args_require = ['title', 'description']

      # check parameter validation
      if len(set(arguments) & set(args_require)) != len(args_require):
        result['code'] = 400
        result['message'] = 'bad request'
        return self.createRes(400, result)
Пример #49
0
  def post(self, **kwargs):
    result = {
      'code': 400,
      'message': 'bad request'
    }
    
    # update user info
    if kwargs.get('uid'):
      if self.get_user() is None:
        result['code'] = 401
        result['message'] = 'unauthorized'
      else:
        
        uid = self.get_user().get('uid')
  
        if kwargs.get('uid') != 'me' and uid != int(kwargs.get('uid')):
          result['code'] = 400
          result['message'] = 'already exists'
          return self.createRes(400, result)
        
        reqInfo = self.arguments
          
        # get user info
        user = Users.get(id=uid)
        if type(user) == ndb.key.Key:
          result['code'] = 400
          result['message'] = 'bad request'
        
        else:
          # using API, user can modify nickname and picture
          available_list = ['nickname', 'picture', 'hanasee', 'language'] + [kwargs.get('attribute')]
    
          reqInfo = []
          for field in self.arguments:
            if field in available_list:
              if hasattr(self.arguments[field], 'FieldStorageClass'):
                dtCreated = datetime.datetime.now()
                filename = "%d" % (time.mktime(dtCreated.timetuple())*1e3 + dtCreated.microsecond/1e3)
                
                image_url = self.create_file(self.arguments.get(field).value, filename, self.arguments.get(field).type)
                setattr(user, field, image_url)
              elif field == 'password':
                if user.password == md5.md5(self.arguments.get('old_password')).hexdigest():
                  setattr(user, field, md5.md5(self.arguments.get('password')).hexdigest())
                else:
                  result['code'] = 401
                  result['message'] = 'invalid password'
              else:
                setattr(user, field, self.arguments.get(field))
          
          if result['code'] != 401:
            user.put()
            
            result['code'] = 200
            result['message'] = 'OK'
            result['User'] = user.to_obj(mine = True)
        
    else:
      arguments = self.arguments
      args_regist = ['email', 'password', 'nickname']
  
      # check parameter validation
      if len(set(arguments) & set(args_regist)) == len(args_regist):
        user = Users.find(self.request.get('email'))
  
        if user:
          result['code'] = 401
          result['message'] = 'already registered'
          #return self.createRes(401, result)
  
        else:
          # check password
          #md5password = md5.md5(self.arguments.get('password')).hexdigest()
  
          # insert as a new user
          user = Users(auto_id=True)
          #user.password = md5password
          user.password = self.arguments.get('password')
          user.set(self.convertRequsetParameter(self.arguments, ['password']))
  
          if ('deviceInfo' in self.session) and (appName in self.session['deviceInfo']):
            deviceInfo = self.session['deviceInfo'][self.request.get('appName')]
  
            # save reg_id in user
            setattr(user, re.sub('\.', '', self.request.get('appName')), deviceInfo['regId'])
            user.put()
  
            # save user in device
            device = ndb.Key(Devices, "%s|%s" % (self.request.get('appName'), deviceInfo['deviceId'])).get()
            setattr(device, 'user', user.key)
            device.put()
  
          self.session['user'] = user.to_obj(mine=True)
          result['code'] = 200
          result['message'] = 'OK'
  
    if result['code'] == 200:
      if self.arguments.get('returnTo', None):
        return self.redirect(str(self.arguments.get('returnTo')))
      else:
        return self.createRes(200, result)
    else:
      if self.arguments.get('returnTo', None):
        options = {
          'returnTo': self.arguments.get('returnTo'),
          'message': result['message']
        };

        if self.get_user():
          options['uid'] = self.get_user().get('uid')
        template = JINJA_ENVIRONMENT.get_template(self.arguments.get('dialog'))
        return self.response.write(template.render(options))
      else:
        return self.createRes(401, result)
Пример #50
0
  def regist(self, **kwargs):
    result = {
      'code': 400,
      'message': 'bad request'
    }

    args_regist = ['email', 'password', 'nickname']

    # check parameter validation
    if len(set(self.arguments) & set(args_regist)) == len(args_regist):
      user = Users.find(self.arguments.get('email'))

      if user:
        result['code'] = 401
        result['message'] = 'already registered'
        #return self.createRes(401, result)

      else:
        # check password
        try:
          md5password = md5.md5(self.arguments.get('password')).hexdigest()
        except UnicodeEncodeError, e:
          logging.error("password = %s" % self.arguments.get('password'))
          return self.createRes(401, result)

        # insert as a new user
        user = Users(auto_id=True)
        user.password = md5password
        user.set(self.convertRequsetParameter(self.arguments, ['password']))

        if ('deviceInfo' in self.session) and ('appName' in self.session['deviceInfo']):
          deviceInfo = self.session['deviceInfo']

          # save reg_id in user
          setattr(user, re.sub('\.', '', '%s_regid' % self.arguments.get('appName')), deviceInfo['regId'])
          user.put()

          # save user in device
          device = ndb.Key(Devices, "%s|%s" % (self.arguments.get('appName'), deviceInfo['deviceId'])).get()
          if device is not None:
            setattr(device, 'user', user.key)
            device.put()

        message = '%s님이 하나시를 시작했습니다.' % user.nickname
        url = 'http://hanasee.com'
        Messages(user=user.key,
          action_user=user.key,
          action='regist',
          settings='system',
          app_name='hanasee',
          message=message,
          url=url).send(['MAIL','SNS'])
        self.session['user'] = user.to_obj(mine=True)
        result['code'] = 200
        result['message'] = 'OK'

      if result['code'] == 200:
        if self.session.get('returnTo', None):
          returnTo = self.session.pop('returnTo')
          return self.redirect(returnTo)
        else:
          result['code'] = 200
          result['message'] = 'OK'
          result['User'] = user.to_obj(mine=True)
          return self.createRes(200, result)
      else:
        if self.session.get('returnTo', None):
          options = {
            'returnTo': self.session.get('returnTo'),
            'message': result['message']
          };

          template = JINJA_ENVIRONMENT.get_template('signin.html')
          return self.response.write(template.render(options))
        else:
          return self.createRes(401, result)
Пример #51
0
    try:
      uid = self.get_user().get('uid') if kwargs.get('uid') == 'me' else int(kwargs.get('uid', 0))
      hid = int(kwargs.get('hid'))
      pid = int(kwargs.get('pid', 0))
    except ValueError, e:
      result['code'] = 400
      result['message'] = 'bad request'
      return self.createRes(401, result)

    if kwargs.get('uid') == 'me' and not self.get_user():
      result['code'] = 401
      result['message'] = 'not logged in'
      return self.createRes(401, result)

    author = Users.get(id=uid)
    if type(author) == ndb.key.Key:
      result['code'] = 401
      result['message'] = 'not allowed'
      return self.createRes(401, result)

    hanasy = Hanasies.get(id=hid, parent=author.key)
    if type(hanasy) == ndb.key.Key:
      result['code'] = 404
      result['message'] = 'not found'
      return self.createRes(404, result)

    if not pid:
      # get all parts in a hanasy
      options = {}
      for item in self.arguments:
Пример #52
0
  def post_backup(self, **kwargs):
    result = {
      'code': 400,
      'message': 'bad request'
    }

    reqInfo = {}
    for item in self.arguments:
      if bool(re.search('\[\d\]', item)):
        if re.sub('\[\d\]', '', item) in reqInfo:
          reqInfo[re.sub('\[\d\]', '', item)].append(self.arguments.get(item))
        else:
          reqInfo[re.sub('\[\d\]', '', item)] = [self.arguments.get(item)]
      elif bool(re.search('\.', item)):
        reqInfo[re.sub('\.', '', item)] = self.arguments.get(item)
      else:
        reqInfo[item] = self.arguments.get(item)

    Users.set(reqInfo)
    return self.createRes(200, {'me':'O'})

    redirect_uri = self.session['returnTo'] if self.session and self.session['returnTo'] else self.arguments.get('returnTo')
    redirect_uri = redirect_uri + '&from=regist' if redirect_uri else null
    del self.session['returnTo']

    if not kwargs.get('id'):
      if not self.arguments.get('email') or not self.arguments.get('password'):
        return self.createRes(400, {'message': 'missing parameter'})

      current = time.time()
      id = (current * 100) + Math.floor(Math.random() * 100)
      key = {
        'id': id.toString(),
        'email': self.arguments.get('email')
      }

      if self.arguments.get('nickname'):
        key['nickname'] = self.arguments.get('nickname')

      reqInfo = {}
      for item in self.arguments:
        reqInfo[item] = self.argum.get(item);

      """
      db.users.regist(key, reqInfo, function(err, user) {
        if err == 'already exists':
          return res.render('regist', {'message': '이메일 또는 닉네임을 사용할 수 없습니다.'})
          return self.createRes(409, {'message': err})
        elif err:
          return res.render('regist', {'message': '알 수 없는 에러가 발생했습니다. 다시 시도해주세요.'})
          return self.createRes(500, {'message': err})
        elif not user:
          return res.render('regist', {'message': err})
          return self.createRes(500, {'message': 'unknown error'})

        del user.password
        self.logIn(user, function(err) {
          if self.session.deviceInfo:
            for (appName in self.session.deviceInfo):
              if self.session.deviceInfo[appName] !== user[appName]:
                regId = {}
                regId[appName] = self.session.deviceInfo[appName].regId
                keyDevice = {'appName': appName, 'deviceId': self.session.deviceInfo[appName].deviceId}
                db.users.update({'id': user.id}, regId)
                db.devices.update(keyDevice, {'user_id': user.id})

          if redirect_uri:
            return res.redirect(redirect_uri)
          else:
            result['code'] = 200
            result['message'] = 'OK'
            result['User'] = user
            return self.createRes(200, user)
        })
      })
      """
    else:
      # modify my userinfo
      if kwargs.get('id') == 'me' or kwargs.get('id') == self.get_user().get('id'):
        if not self.get_user():
          return self.createRes(401, {'message': 'not logged in'})

        key = {
          id: self.get_user().get('id')
        }

        reqInfo = {}
        for item in self.arguments:
          reqInfo[item] = self.arguments.get(item);

        # cannot modify id
        del reqInfo['id']
        del reqInfo['email']
        del reqInfo['kakao']


        if kwargs.get('attribute') == 'connection':
          if not reqInfo.get('connectionProvider'):
            return self.createRes(400, {'message': 'missing parameter'})

          unique = reqInfo.get('connectionProvider')[0:3]+self.get_user().get('id')[2:4]+str(time.time())
          md5.md5(unique).hexdigest()

          reqInfo[reqInfo['connectionProvider']] = connectionKey
          del reqInfo['connectionProvider']
        """
        db.users.update(key, reqInfo, function(err, user) {
          del user['password']
          del user['kakao']
          del user['facebook']

          self.logIn(user, function(err) {
            if kwargs.get('attribute') == 'connection':
              user['connectionKey'] = connectionKey

            return self.createRes(200, user)
          })
        })
        """
      elif self.get_user().get('id') != kwargs.get('id'):
        return self.createRes(401, {'message': 'cannot modify others'})
Пример #53
0
 def isAuthor(self):
     #user_name_cookie = self.get_secure_cookie('username', '')
     email_cookie = self.get_secure_cookie('email', '')
     password_cookie = self.get_secure_cookie('password', '')
     from model.users import Users
     return Users.check_user_or_email_password(email_cookie, password_cookie)
Пример #54
0
  def signin(self, **kwargs):
    logging.error("signin")
    result = {
      'code': 400,
      'message': 'bad request'
    }

    args_signin = ['email', 'password']
    args_device = ['deviceId', 'appName']
    args_oauth = ['type']

    # check parameter validation
    if len(set(self.arguments) & set(args_device)) == len(args_device):
      # device signin
      device_key = ndb.Key('Devices', '%s|%s' % (self.arguments.get('appName'), self.arguments.get('deviceId')))
      device = device_key.get()

      if device and getattr(device, 'user', None) is not None and getattr(device, 'user').get() is not None:
        user = getattr(device, 'user').get()
        self.session['user'] = user.to_obj(mine=True)
        setattr(user, '%s_regid' % self.arguments.get('appName'), device.regId)
        user.put()

        message = '로그인 하셨습니다'
        url = 'http://hanasee.com'
        Messages(user=user.key,
          action_user=user.key,
          action='signin',
          settings='system',
          app_name='hanasee',
          message=message,
          url=url)

        if hasattr(self.session, 'returnTo'):
          return self.redirect(self.session.pop('returnTo'))

        else:
          result['code'] = 200
          result['message'] = 'OK'
          result['User'] = user.to_obj(mine=True)
          return self.createRes(200, result)

      # no information in device
      elif self.arguments.get('returnTo') is not None:
        options = {
          'returnTo': self.arguments.get('returnTo'),
          'appName': self.arguments.get('appName'),
          'state': self.arguments.get('state')
        }

        template = JINJA_ENVIRONMENT.get_template('signin.html')
        return self.response.write(template.render(options))

      else:
        result['code'] = 401
        result['message'] = 'unauthorized'
        return self.createRes(401, result)

    elif len(set(self.arguments) & set(args_signin)) == len(args_signin):
      # email signin
      user = Users.find(self.arguments.get('email'))

      if not user:
        result['code'] = 401
        result['message'] = 'invalid email address' + self.arguments.get('email')
        #return self.createRes(401, result)

      else:
        # check password
        md5password = md5.md5(self.arguments.get('password')).hexdigest()
        if md5password != user.password:
          result['code'] = 401
          result['message'] = 'invalid password'
          #return self.createRes(401, result)

        else:
          # success to login
          # device info
          if ('deviceInfo' in self.session):
            deviceInfo = self.session['deviceInfo']

            # save reg_id in user
            setattr(user, re.sub('\.', '', '%s_regid' % deviceInfo.get('appName')), deviceInfo.get('regId'))
            user.put()

            # save user in device
            device_key = ndb.Key('Devices', '%s|%s' % (deviceInfo.get('appName'), deviceInfo.get('deviceId')))
            device = device_key.get()

            setattr(device, 'user', user.key)
            device.put()

            self.session.pop('deviceInfo')

          message = '로그인 하셨습니다'
          url = 'http://hanasee.com'
          Messages(
            user=user.key,
            action_user=user.key,
            action='signin',
            settings='system',
            app_name='hanasee',
            message=message,
            url=url)

          self.session['user'] = user.to_obj(mine=True)
          result['code'] = 200
          result['message'] = 'OK'

      if result['code'] == 200:
        if self.session.get('returnTo', None):
          returnTo = self.session.pop('returnTo')
          return self.redirect(returnTo)
        else:
          result['code'] = 200
          result['message'] = 'OK'
          result['User'] = user.to_obj(mine=True)
          return self.createRes(200, result)
      else:
        if self.session.get('returnTo', None):
          options = {
            'returnTo': self.session.get('returnTo'),
            'message': result['message'],
            'state': self.session.get('state')
          };

          template = JINJA_ENVIRONMENT.get_template('signin.html')
          return self.response.write(template.render(options))
        else:
          return self.createRes(401, result)
    elif kwargs.get('type'):
      authomatic = Authomatic(config=CONFIG, secret='a-long-secret-string')
      results = authomatic.login(Webapp2Adapter(self), kwargs.get('type'))
      if results:
        if results.error:
          pass
        elif results.user:
          if not results.user.id:
            results.user.update()

          # find existed connection
          connection = Connections.get(id="%s|%s" % (results.provider.name, results.user.id))
          user = None

          if type(connection) == ndb.key.Key:
            connection = Connections(id="%s|%s" % (results.provider.name, results.user.id))

          if connection.user is not None:
            user = connection.user.get()
          elif getattr(results.user, 'email') is not None:
            user = Users.find(results.user.email)

          isNewUser = False

          if user is None:
            user = Users(auto_id=True)
            user.email = getattr(results.user, 'email')
            isNewUser = True

          connection.user = user.key

          if getattr(user, 'nickname') is None:
            if results.provider.name == 'kakao':
              try:
                user.nickname = results.user.data.get(u'properties').get(u'nickname')
              except KeyError, e:
                logging.error('kakao error : ' + e)

                if self.session.get('returnTo', None):
                  template = JINJA_ENVIRONMENT.get_template('signin.html')
                  options = {
                    'returnTo': self.arguments.get('returnTo'),
                    'appName': self.arguments.get('appName'),
                    'state': self.arguments.get('state')
                  }
                  options['message'] = 'internal error'
                  return self.response.write(template.render(options))
                else:
                  result['code'] = 500
                  result['message'] = 'internal error'
                  return self.createRes(500, result)
            else:
              user.nickname = results.user.name

          if getattr(user, 'picture') is None:
            if results.provider.name == 'kakao':
              try:
                user.picture = results.user.data.get(u'properties').get(u'profile_image')
              except KeyError, e:
                logging.error(results.user.data)
            elif results.provider.name == 'fb':
              url = 'https://graph.facebook.com/{}?fields=picture'
              url = url.format(results.user.id)
              response = results.provider.access(url)
              user.picture = response.data.get('picture').get('data').get('url')
            elif results.provider.name == 'tw':
              url = 'https://api.twitter.com/1.1/users/show.json?user_id={}'
              url = url.format(results.user.id)
              response = results.provider.access(url)
              user.picture = response.data.get('profile_image_url')
            elif results.provider.name == 'google':
              user.picture = results.user.picture

          # device info
          if ('deviceInfo' in self.session):
            deviceInfo = self.session['deviceInfo']

            # save reg_id in user
            setattr(user, re.sub('\.', '', '%s_regid' % deviceInfo.get('appName')), deviceInfo.get('regId'))
            user.put()

            # save user in device
            device = ndb.Key(Devices, "%s|%s" % (deviceInfo.get('appName'), deviceInfo.get('deviceId'))).get()
            setattr(device, 'user', user.key)
            device.put()

            self.session.pop('deviceInfo')

          logging.error("qqqq")

          # registered: register message
          if isNewUser:
            logging.error("new user")
            message = '%s님이 하나시를 시작했습니다.' % user.nickname
            url = 'http://hanasee.com'
            Messages(user=user.key,
              action_user=user.key,
              action='regist',
              settings='system',
              app_name='hanasee',
              message=message,
              url=url).send(['MAIL','SNS'])

          # otherwise: sign-in message
          else:
            message = '로그인 하셨습니다'
            url = 'http://hanasee.com'
            Messages(
              user=user.key,
              action_user=user.key,
              action='signin',
              settings='system',
              app_name='hanasee',
              message=message,
              url=url)

          self.session['user'] = user.to_obj(mine=True)

          user.provider = results.provider.name
          setattr(user, results.provider.name, results.provider.credentials.serialize())

          connection.put()
          user.put()

          if self.session.get('returnTo', None):
            returnTo = self.session.pop('returnTo')
            return self.redirect(returnTo)
          else:
            result['code'] = 200
            result['message'] = 'OK'
            result['User'] = user.to_obj(mine=True)
            return self.createRes(200, result)
Пример #55
0
      uid = self.get_user().get('uid') if kwargs.get('uid') == 'me' else int(kwargs.get('uid', 0))
    except ValueError, e:
      result['code'] = 400
      result['message'] = 'bad request'
      return self.createRes(400, result)
    except AttributeError, e1:
      result['code'] = 400
      result['message'] = 'bad request'
      return self.createRes(400, result)

    if kwargs.get('uid') == 'me' and not self.get_user():
      result['code'] = 401
      result['message'] = 'not logged in'
      return self.createRes(401, result)

    user = Users.get(id=int(uid))
    me = self.get_user().get('uid') if self.get_user() else None
    if type(user) == ndb.key.Key:
      # cannot find user
      result['code'] = 401
      result['message'] = 'invalid uid'
      return self.createRes(401, result)
    elif user.key.id() == me:
      result['code'] = 200
      result['message'] = 'OK'
      result['User'] = user.to_obj(mine = True)
      return self.createRes(200, result)
    else:
      result['code'] = 200
      result['message'] = 'OK'
      result['User'] = user.to_obj()