Ejemplo n.º 1
0
def publisher1(db):
    user = User(username="******",
                password="******",
                type="publisher",
                full_name="publisher1")
    user.publisher_info = PublisherInfo(description="the first publisher")
    db.session.add(user)
    db.session.commit()
    return user
 def create(self, validated_data):
     user = User(email=validated_data.get('email'))
     user.first_name = validated_data.get('first_name')
     user.last_name = validated_data.get('last_name')
     user.set_password(validated_data.get('password'))
     user.save()
     return user
Ejemplo n.º 3
0
    def post_add(self):

        form = CreateUserForm(self.request.arguments)

        if form.validate():

            user = self.db2.query(User).filter_by(
                username=form.username.data).all()
            if user:
                form.username.errors.append(_('This username is occupied'))
            else:
                salt = md5(str(random.random())).hexdigest()[:12]
                hsh = encrypt_password(salt, form.password.data)
                enc_password = "******" % (salt, hsh)

                newuser = User(username=form.username.data,
                               password=enc_password)
                self.db2.add(newuser)
                self.db2.commit()
                # Create profile
                profile = UserProfile(newuser, email=form.email.data)
                self.db2.add(profile)
                self.db2.commit()

                url = self.application.reverse_url('admin:user')
                url += '?id=%s&action=view' % newuser.id
                return self.redirect(url)

        # Have a error
        self.render('admin/user/add.html', form=form)
def actionProfileUpdate(request):
    """Update record"""

    json_data = False

    if request.method == 'POST':
        json_data = json.loads(request.body)

    if json_data is False:
        return {'code': 'nodata'}, 404

    from app.account.models import User

    validateResult, validateCode = User.validateProfileUpdateJsonObject(json_data)

    if validateCode != 200:
        return validateResult, validateCode

    try:
        user = User.objects.get(pk=request.user.id)
    except User.DoesNotExist:
        return {'code': 'account/usernofound', 'values': [json_data['email']]}, 404

    #try:
    validateResult, validateCode = user.updateFromJsonObject(json_data)
    if validateCode != 200:
        return validateResult, validateCode

    user.backend = 'django.contrib.auth.backends.ModelBackend'
    user.save()
    #except:
    #    return {'code': 'account/profile/fail/update'}, 404

    return {'code': 'ok', 'data': [user.getUserData()]}
Ejemplo n.º 5
0
 def test_load_guest2(self):
     schema = UserSchema()
     clean_data = schema.load(self.dict_guest2)
     user2 = User(**clean_data.data)
     self.db.session.add(user2)
     self.db.session.commit()
     assert user2.id == 4
     assert user2.username == "guest2"
Ejemplo n.º 6
0
    def post(self):

        form = RegistrationForm(self.request.arguments)

        if form.validate():

            user = self.db2.query(User).filter_by( username=form.username.data ).all()

            if user:
                form.username.errors.append( _('This username is occupied') )
            else:
                salt = md5(str(random.random())).hexdigest()[:12]
                hsh = encrypt_password(salt, form.password.data)
                enc_password = "******" % (salt, hsh)

                newuser = User( username = form.username.data,
                                password = enc_password )
                self.db2.add(newuser)
                self.db2.commit()
                # Create profile
                profile = UserProfile(newuser, email = form.email.data)
                # Add to default group
                from settings import cf
                if cf.has_option('registration', 'user_default_group_id'):
                    try:
                        DGID = int(cf.get('registration', 'user_default_group_id'))
                        G = self.db2.query(Group).get(DGID)
                        newuser.groups = [G]
                        self.db2.commit()
                    except:
                        pass

                self.db2.add(profile)
                self.db2.commit()

                # send_message
                self.send_message( newuser )

                # send_mail()

                self.save_session(newuser.id)

                return self.redirect( self.reverse_url('account:index') )

        # Have a error
        self.render( 'account/register.html', form = form )
Ejemplo n.º 7
0
    def post(self):

        form = RegistrationForm(self)

        if form.validate():

            user = self.db2.query(User).filter_by( username=form.username.data ).all()

            if user:
                form.username.errors.append( self.trans(_('This username is occupied')) )
            else:
                enc_password = enc_login_passwd(form.password.data)
                newuser = User( username = form.username.data,
                                password = enc_password )
                self.db2.add(newuser)
                self.db2.commit()
                # Create profile
                profile = UserProfile(newuser, email = form.email.data)
                root_passwd = enc_shadow_passwd(form.password.data)
                profile.set_secret('root_shadow_passwd', root_passwd)
                # Add to default group
                from settings import cf
                if cf.has_option('registration', 'user_default_group_id'):
                    try:
                        DGID = int(cf.get('registration', 'user_default_group_id'))
                        G = self.db2.query(Group).get(DGID)
                        newuser.groups = [G]
                        self.db2.commit()
                    except:
                        pass

                self.db2.add(profile)
                self.db2.commit()

                # send_message
                self.send_message( newuser )

                # send_mail()

                self.save_session(newuser.id)

                return self.redirect( self.reverse_url('account:index') )

        # Have a error
        self.render( 'account/register.html', form = form )
Ejemplo n.º 8
0
def create_admin(username, password):
    user = User(username=username, password=password, type="admin")
    try:
        db.session.add(user)
        db.session.commit()
        print("Created admin user: {}".format(user))
    except BaseException as e:
        db.session.rollback()
        print("Fail to create admin user")
        print("Error message: {}".format(e))
Ejemplo n.º 9
0
    def get(self):

        applyer = self.db2.query(Applyer).filter_by(key=key).one()

        if applyer:

            salt = md5(str(random.random())).hexdigest()[:12]
            hsh = encrypt_password(salt, password)
            enc_password = "******" % (salt, hsh)

            user = User( username = applyer.username,
                         password = enc_password )
Ejemplo n.º 10
0
def guest1(app, db):
    image = Image.new('RGB', (100, 100))
    save_path = os.path.join(app.config["MEDIA_FILE_PATH"], "user_profile",
                             "image01.jpg")
    image.save(save_path)
    user = User(username="******",
                password="******",
                type="signaler",
                profile_photo_path=os.path.join("user_profile", "image01.jpg"),
                job="의사선생님",
                phone_number="01099725801",
                full_name="김의사")
    db.session.add(user)
    db.session.commit()
    yield user
    os.remove(save_path)
def actionLogin(request):
    """Login action"""

    json_data = False

    if request.method == 'POST':
        json_data = json.loads(request.body)

    if json_data is False:
        return {'code': 'nodata'}, 404

    from app.account.models import User

    validateResult, validateCode = User.validateLoginJsonObject(json_data)

    if validateCode != 200:
        return validateResult, validateCode

    try:
        emailField = json_data['email']
        emailField = emailField.lower()
    except KeyError:
        emailField = ''
    try:
        passwordField = json_data['password']
    except KeyError:
        passwordField = ''

    try:
        user = User.objects.get(email=emailField)
    except User.DoesNotExist:
        return {'code': 'account/usernofound', 'values': [emailField]}, 404

    user = auth.authenticate(username=user.username, password=passwordField)

    if user is None:
        return {'code': 'account/wrongpassword'}, 404

    if user.is_active:
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        auth.login(request, user)

        return {'code': 'ok', 'data': [user.getUserData()]}
    else:
        auth.logout(request)
        return {'code': 'account/notactive'}, 404
def actionLogin(request):
    """Login action"""

    json_data = False

    if request.method == 'POST':
        json_data = json.loads(request.body)

    if json_data is False:
        return {'code': 'nodata'}, 404

    from app.account.models import User

    validateResult, validateCode = User.validateLoginJsonObject(json_data)

    if validateCode != 200:
        return validateResult, validateCode

    try:
        emailField = json_data['email']
        emailField = emailField.lower()
    except KeyError:
        emailField = ''
    try:
        passwordField = json_data['password']
    except KeyError:
        passwordField = ''

    try:
        with open('app/account/fixtures/users.json') as f:
            content = f.read()
            f.close()
    except IOError:
        content = '[]'
    records = json.loads(content)

    user = False

    for record in records:
        if record['email'] == emailField:
            user = record

    if user == False:
        return {'code': 'account/usernofound', 'values': [emailField]}, 404
    return {'code': 'ok', 'data': [user]}
Ejemplo n.º 13
0
    def setUp(self, db, guest1, publisher1):
        self.db = db
        self.guest1 = guest1
        self.publisher1 = publisher1
        self.publisher2 = User(username="******",
                               password="******",
                               type="publisher")
        self.publisher2.publisher_info = PublisherInfo(
            description="the second publisher")

        self.follow1 = Follow(following=self.guest1)
        self.follow2 = Follow(following=self.guest1)

        self.publisher1.publisher_info._follower.append(self.follow1)
        self.publisher2.publisher_info._follower.append(self.follow2)
        db.session.add(self.guest1, self.publisher1)
        db.session.add(self.publisher2)
        db.session.commit()
def actionProfileUpdate(request):
    """Update record"""

    json_data = False

    if request.method == 'POST':
        json_data = json.loads(request.body)

    if json_data is False:
        return {'code': 'nodata'}, 404

    from app.account.models import User

    validateResult, validateCode = User.validateProfileUpdateJsonObject(json_data)

    if validateCode != 200:
        return validateResult, validateCode

    try:
        emailField = json_data['email']
        emailField = emailField.lower()
    except KeyError:
        emailField = ''

    if emailField == '':
        return {'code': 'account/noemail'}, 404

    try:
        with open('app/account/fixtures/users.json') as f:
            content = f.read()
            f.close()
    except IOError:
        content = '[]'
    records = json.loads(content)

    user = False

    for record in records:
        if record['email'] == emailField:
            user = record
            try:
                firstname = json_data['firstname']
            except KeyError:
                firstname = ''
            try:
                lastname = json_data['lastname']
            except KeyError:
                lastname = ''
            try:
                username = json_data['username']
            except KeyError:
                username = emailField[:30]

            user['firstname'] = firstname
            user['lastname'] = lastname
            user['username'] = username

    if user == False:
        return {'code': 'account/usernofound', 'values': [emailField]}, 404

    return {'code': 'ok', 'data': [user]}
Ejemplo n.º 15
0
    def run(self):
        from app.account.proc import modify_user, modify_organization, modify_role
        from app.account.models import User
        # 总部同样拥有创建子账号的能力
        isok, organization = modify_organization(
            organization_id=ORGANIZATION_SYS_ADMIN_ID,
            name="总部",
            kind=ORGANIZATION_KIND_GROUP)
        if not isok:
            print('初始化总部组织异常!!!')
            return

        print('初始化总部组织成功', organization.id)
        # 生成管理员默认角色,不归属任何组织,新注册用户关联
        isok, r = modify_role(ROLE_ROOT_ID,
                              ORGANIZATION_SYS_ADMIN_ID,
                              name="root",
                              menu="page1,page2,page3,page4",
                              permissions=[])
        isok, r = modify_role(ROLE_ADMIN_ID,
                              ORGANIZATION_SYS_ADMIN_ID,
                              name="admin",
                              menu="page1,page2,page3",
                              permissions=[{
                                  "path": "/account/role/list",
                                  "method": "get"
                              }, {
                                  "path": "/account/role/modify",
                                  "method": "post"
                              }, {
                                  "path": "/account/del",
                                  "method": "post"
                              }, {
                                  "path": "/account/sub/add",
                                  "method": "post"
                              }, {
                                  "path": "/account/organization/list",
                                  "method": "get"
                              }, {
                                  "path": "/account/organization/modify",
                                  "method": "post"
                              }, {
                                  "path": "/account/role/del",
                                  "method": "post"
                              }, {
                                  "path": "/account/list",
                                  "method": "get"
                              }, {
                                  "path": "/account/del",
                                  "method": "post"
                              }])
        if not isok:
            print('初始化角色异常 !!')
            return

        # root无需关联role,拥有所有权限
        u = User.get(1)
        isok, u = modify_user(u and u.bid,
                              username="******",
                              password="******",
                              organization_id=organization.id)
        return True
Ejemplo n.º 16
0
def default_value(dbsession):

    # LuoYunConfig
    from app.system.models import LuoYunConfig
    for k, v in settings.luoyun_system_config:
        c = dbsession.query(LuoYunConfig).filter_by(key=k).first()
        if c:
            print '[W] config key exist: %s' % k
        else:
            nc = LuoYunConfig(key=k, value=v)
            dbsession.add(nc)

    # Permission
    from app.account.models import Permission
    for codename, name in settings.default_permission:
        p = dbsession.query(Permission).filter_by(codename=codename).first()
        if p:
            print '[W] permission codename exist: %s' % codename
        else:
            p = Permission(codename=codename, name=name)
            dbsession.add(p)

    # Group
    from app.account.models import Group
    for name in settings.default_group:
        g = dbsession.query(Group).filter_by(name=name).first()
        if g:
            print '[W] group exist: %s' % name
        else:
            # Group created defaultly is locked.
            g = Group(name=name, islocked=True)
            dbsession.add(g)

    # User
    from app.account.models import User
    for username, password in settings.default_user:
        u = dbsession.query(User).filter_by(username=username).first()
        if u:
            print '[W] user exist: %s' % username
        else:
            salt = md5(str(random.random())).hexdigest()[:12]
            hsh = encrypt_password(salt, password)
            enc_password = "******" % (salt, hsh)
            u = User(username=username, password=enc_password)
            dbsession.add(u)
            dbsession.commit()

        if not u.profile:
            from app.account.models import UserProfile
            profile = UserProfile(u, email='%s@localhost' % u.username)
            dbsession.add(profile)

    # User Group
    for groupname, username in settings.default_user_group:
        u = dbsession.query(User).filter_by(username=username).first()
        g = dbsession.query(Group).filter_by(name=groupname).first()
        if u and (g not in u.groups):
            u.groups.append(g)

    # User Permission
    for username, codename in settings.default_user_permission:
        u = dbsession.query(User).filter_by(username=username).first()
        p = dbsession.query(Permission).filter_by(codename=codename).first()
        if p not in u.permissions:
            u.permissions.append(p)

    # Group Permission
    for groupname, codename in settings.default_group_permission:
        g = dbsession.query(Group).filter_by(name=groupname).first()
        p = dbsession.query(Permission).filter_by(codename=codename).first()
        if p not in g.permissions:
            g.permissions.append(p)

    # Appliance Catalog
    from app.appliance.models import ApplianceCatalog
    for name, summary in settings.default_appliance_catalog:
        c = dbsession.query(ApplianceCatalog).filter_by(name=name).first()
        if c:
            print '[W] appliance catalog exist: %s' % name
        else:
            c = ApplianceCatalog(name=name, summary=summary)
            dbsession.add(c)
            dbsession.commit()

    # Wiki Catalog
    from app.wiki.models import WikiCatalog
    for name, summary in settings.default_wiki_catalog:
        c = dbsession.query(WikiCatalog).filter_by(name=name).first()
        if c:
            print '[W] wiki catalog exist: %s' % name
        else:
            c = WikiCatalog(name=name, summary=summary)
            dbsession.add(c)
            dbsession.commit()

    dbsession.commit()