Beispiel #1
0
def register():
    if session.get('username'):
        return redirect(url_for('index'))

    form = RegistrationForm()
    if form.validate_on_submit():
        user_id = User.objects.count()
        user_id += 1

        email = form.email.data
        password = form.password.data
        first_name = form.first_name.data
        last_name = form.last_name.data

        user = User(user_id=user_id,
                    email=email,
                    first_name=first_name,
                    last_name=last_name)

        user.set_password(password)
        user.save()
        flash("You are successfully registered", "success")
        return redirect(url_for('index'))

    return render_template("register.html",
                           title="Register",
                           form=form,
                           register=True)
Beispiel #2
0
    def post(self, request, *args, **kwargs):
        print "post received"
        data = request.DATA
        print "data received"

        try:
            print "trying to get data"
            fb_id = data['fb_id']
            oauth = data['oauth']
            email = data['email']
        except KeyError:
            error = {'error': "Invalid request"}
            return Response(error,
                            status=status.HTTP_400_BAD_REQUEST)

        print "trying to get User"
        try:
            user = User(fb_id=fb_id, email=email)
            user.save()
        except Exception:
            content = {'content': 'account already exists'}
            return Response(content, status=status.HTTP_200_OK)
        print("starting redis queue")
        django_rq.enqueue(run_queue, fb_id, oauth, email, user)
        print("redis queue started")
        return Response(status=status.HTTP_201_CREATED)
Beispiel #3
0
def adduser(request):
    user = User()
    arr = ['张三', '李四', '王五', '赵柳', '田七']
    temp = random.randrange(0, len(arr))
    user.u_name = arr[temp] + '-' + str(random.randrange(10, 100))

    user.save()
    return HttpResponse('添加用户成功:' + user.u_name)
Beispiel #4
0
    def create_user(self, data, is_active=True):
        valid_input, valid_input_message = self.validate_signup_payload(data)
        if not valid_input:
            return {"success": valid_input, "message": valid_input_message}
        is_exists, exists_message = self.check_user_existence(
            data["email"], data["phone"])
        if is_exists:
            return {"success": True, "message": exists_message}

        try:
            hash_text = data["email"] + data["phone"] + data["full_name"]
            hash_object = hashlib.md5(hash_text)
            unique_hash = hash_object.hexdigest()
            try:
                validation = Schema({
                    'full_name':
                    And(basestring,
                        lambda n: 30 >= len(n) >= 3,
                        error="Minimum 3 Characters are Required"),
                    'email':
                    And(basestring,
                        lambda n: len(n) >= 3,
                        error="Minimum 3 Characters are Required"),
                    'phone':
                    And(basestring,
                        lambda n: len(n) >= 6,
                        error="Minimum 6 Characters are Required"),
                    "password":
                    And(basestring,
                        lambda n: len(n) >= 6,
                        error="Minimum 6 Characters are Required")
                }).validate(data)
            except SchemaError as e:
                error = e.message
                return {"success": False, "message": error}

            account_create = User()
            user_id = str(uuid.uuid4())
            account_create.username = user_id
            account_create.email = data['email']
            account_create.phone = data['phone']
            account_create.full_name = data['full_name']
            account_create.is_active = is_active
            account_create.password = self.pwd_context.encrypt(
                data['password'])
            account_create.token = self.generate_api_token(unique_hash)
            account_create.save()

            return {"success": True, "message": "Created User Successfully"}

        except Exception as e:
            print(traceback.format_exc())
Beispiel #5
0
def user_add(user_dict):
    user_name = user_dict['new_name']
    user_password = user_dict['new_password']
    user_question = user_dict['question']
    user_answer = user_dict['answer']
    try:
        User.objects.get(user_name=user_name).first()
    except Exception:
        user = User(user_name=user_name,
                    user_password=user_password,
                    question=user_question,
                    answer=user_answer)
        user.save()
    else:
        return u'该用户名已被注册'
    return u"1"
Beispiel #6
0
def createuser():
    '''Creates a new user for the website.'''
    name = prompt('Username')
    raw_pwd = prompt_pass('Password')
    confirm_pwd = prompt_pass('Confirm Password')

    user = User()
    data = MultiDict(dict(name=name, raw_pwd=raw_pwd, confirm_pwd=confirm_pwd))
    form = SignupForm(data, obj=user, csrf_enabled=False)
    if form.validate():
        form.populate_obj(user)
        user.save()

        print('User was successfully created.')
    else:
        for field, errors in form.errors.iteritems():
            field_text = getattr(form, field).label.text
            for error in errors:
                print('[Error] {0}: {1}'.format(field_text, error))
Beispiel #7
0
def user_create():
    form = UserForm(request.form)
    form.action = url_for('admin:user:create')
    form.level.choices = get_level()
    if form.validate_on_submit():
        user = User()
        user.email = form.email.data
        user.password = form.password.data
        user.no_induk = form.no_induk.data
        level = Level.get(Level.id == form.level.data)
        jenkel = form.profile.jenis_kelamin.data
        nama = form.profile.nama.data
        profile = Profile.create(nama=nama, jenis_kelamin=jenkel)
        user.level = level
        user.profile = profile
        user.save()
        return redirect(url_for('admin:user:list'))
    if form.errors:
        print form.errors
    return render_template('admin/user/create.html', form=form)
Beispiel #8
0
    def post(self, uk):
        user_data = self.get_data()
        user_data['deviceid'] = "test-test-test"
        user = User()
        user.from_dict(user_data)
        user.generate_secret()
        user.generate_avatar_path()

        if user.save():
            self.set_status(201)
            self.set_header('Location', user.get_link())
        else:
            raise HTTPError(500, 'Save avatar user info error.')

        self.finish()
Beispiel #9
0
    def post(self, phn):
        user = User()

        data = self.get_data()
        user.from_dict(data)
        # after the phone set in
        user.generate_avatar_path()

        if user.save():
            self.set_status(201)
            self.set_header('Location', user.get_link())
            msg = self.message("Created Success.")
        else:
            self.set_status(400)
            msg = self.message("name,phone,password field are required.")
        
        self.render_json(msg)
Beispiel #10
0
    def _on_auth(self, outer_user):
        if not outer_user:
            raise HTTPError(500, "Douban auth failed.")

        auth_id = "%s_%s" % (Auth.DOUBAN, outer_user['access_token']['douban_user_id'])
        auth = Auth.query.get(auth_id)
        user = User.query.get_by_userkey(self.get_secure_cookie('userkey', None)) or auth and auth.user
        self.clear_cookie('userkey')

        # create or update the user
        if user is None and auth is None:
            did = self.get_secure_cookie('uid', None)
            self.clear_cookie('uid')
            if not did:
                raise HTTPError(500, "Douban auth failed.")
            # user data
            user_data = {}
            user_data['userkey'] = auth_id
            user_data['name'] = outer_user['name']
            user_data['avatar'] = outer_user['avatar']
            user_data['brief'] = outer_user['brief']
            user_data['deviceid'] = did

            user = User()
            user.from_dict(user_data)

            user.generate_secret()
            if not user.save():
                raise HTTPError(500, 'Save auth user info error.')

        # auth data
        auth_data = {}
        auth_data['site_label'] = Auth.DOUBAN
        auth_data['access_token'] = outer_user['access_token']['key']
        auth_data['access_secret'] = outer_user['access_token']['secret']
        auth_data['expired'] = outer_user['expired']
        auth_data['user_id'] = user.id
        auth_data['site_user_id'] = auth_id

        # create or update the auth
        if auth is None:
            auth = Auth()

        auth.from_dict(auth_data)
        if not auth.save():
            raise HTTPError(500, "Failed auth with douban account.")

        # send to douban 
        #sns_data = {
        #        'token': auth.access_token,
        #        'secret': auth.access_secret,
        #        'label': auth.DOUBAN,
        #        'content': u"我正在使用乐帮,乐帮是一款基于LBS的帮助应用, 旨在让你在有困难时能更容易地得到帮助。请关注乐帮小站http://site.douban.com/135015/"
        #        }
        #http_client = httpclient.HTTPClient()
        #try:
        #    http_client.fetch(
        #            options.mquri,
        #            body="queue=snspost&value=%s" % self.json(sns_data),
        #            method='POST',
        #            )
        #except httpclient.HTTPError, e:
        #    pass

        self.render_json(auth.user.user2dict4auth() if auth.user.id>0 else {})
        self.finish()