Exemplo n.º 1
0
def create_user_view(request):
    if request.method == 'GET':
        form = CreateUserForm()
        return render(request, 'create_user.html', {'form': form})
    elif request.method == 'POST':
        form = CreateUserForm(request.POST)

        if form.is_valid():
            email = form.cleaned_data['email_address']
            password = form.cleaned_data['password']
            confirm_password = form.cleaned_data['password_repeat']

            if password == confirm_password:
                # check if user exists
                user = User.objects.filter(username=email).first()
                if not user:
                    new_user = User.objects.create_user(username=email,
                                                        email=email,
                                                        password=password)
                    new_user.save()
                    return HttpResponseRedirect('/home')
                else:
                    error = {'msg': 'Account already exists'}
                    return render(request, 'create_user.html', {
                        'form': form,
                        'error': error
                    })
            else:
                error = {'msg': 'Passwords are not the same'}
                return render(request, 'create_user.html', {
                    'form': form,
                    'error': error
                })
Exemplo n.º 2
0
def register():
    form = CreateUserForm()
    if form.validate_on_submit():
        if db.session.query(User).filter_by(email=form.email.data).first():
            flash("Email already exists, log in!")
            return redirect(url_for("login"))

        hashed_password = generate_password_hash(
            form.password.data,
            method='pbkdf2:sha256',
            salt_length=8
        )

        new_user = User()
        new_user.email = form.email.data
        new_user.name = form.name.data
        new_user.password = hashed_password

        db.session.add(new_user)
        db.session.commit()

        login_user(new_user)
        return redirect(url_for("get_all_posts"))

    return render_template("register.html", form=form, current_user=current_user)
Exemplo n.º 3
0
def register():
    form = CreateUserForm()

    if form.validate_on_submit():
        email = form.email.data
        user = User.query.filter_by(email=email).first()
        if user:
            flash("An account already exists for this email. Please log in instead.")
            return redirect(url_for("login"))
        else:
            encrypted_pass = generate_password_hash(
                password=form.password.data,
                method='pbkdf2:sha256',
                salt_length=8
            )
            new_user = User(
                email=form.email.data,
                name=form.name.data,
                password=encrypted_pass
            )
            db.session.add(new_user)
            db.session.commit()
            login_user(new_user)
            return redirect(url_for('get_all_posts'))
    return render_template("register.html", form=form)
Exemplo n.º 4
0
def create_user():
    form = CreateUserForm()
    if form.validate_on_submit():
        if request.method == "POST":
            login = request.form['login']
            password = request.form['password']
            email = request.form['email']
            if not verify_psswd(password):
                flash('Your password is too weak!!')
                return redirect('/new_user')

            u = User.query.filter_by(login=login).first()
            if u:
                flash('Your data is not acceptable')
                return redirect('/new_user')

            user = User(login=login,
                        password=generate_password_hash(password,
                                                        method='sha256'),
                        email=email,
                        loggings=0)
            try:
                db.session.add(user)
                db.session.commit()
                return redirect('/')
            except:
                return "Your data is bad! Try again"
    return render_template("new_user.html", form=form)
Exemplo n.º 5
0
def addprofile():
    userform = CreateUserForm()
    if request.method == 'POST':
        if userform.validate_on_submit():
            firstname  = userform.firstname.data
            lastname   = userform.lastname.data
            email      = userform.email.data
            biography  = userform.biography.data
            location   = userform.location.data
            sex        = userform.gender.data
            
            created_on = format_date_joined()
            
            photo      = userform.photo.data
            filename   = photo.filename
            photo.save(os.path.join(app.config['UPLOAD_FOLDER'],filename)) 
            
            newUser=UserProfile(first_name=firstname,last_name=lastname,email=email,location=location,sex=sex,created_on=created_on,filename=filename,biography=biography)
            db.session.add(newUser)
            db.session.commit()
            
            flash("User Created")
            return redirect(url_for("viewprofiles"))
        else:
            flash_errors(userform)

            
    return render_template('profile.html',form=userform)
Exemplo n.º 6
0
def create_user():
    user = current_user
    title = 'Create User'
    header = 'Create a User'

    form = CreateUserForm()
    if form.validate_on_submit():
        hashed_password = hashlib.sha512(form.password.data).hexdigest()
        new_user = User(nickname=form.nickname.data,
                        email=form.email.data,
                        password=hashed_password)
        if form.is_admin.data:
            new_user.role = ROLE_ADMIN

        try:
            db.session.add(new_user)
            db.session.commit()
            flash('User "' + form.nickname.data + '" created!')
            return redirect('/index')
        except IntegrityError as e:
            flash(e.message)
            return redirect('/create_user')

    return render_template('create_user.html',
                           user=user,
                           title=title,
                           header=header,
                           form=form)
Exemplo n.º 7
0
def createuser():
    form = CreateUserForm()
    error = None
    if (request.method == "POST"):
        if form.validate() == False:
            flash_errors(form)
            return redirect(url_for('createuser', error=error))
        else:
            uid = random.randint(1, 1000)
            firstname = form.firstname.data
            lastname = form.lastname.data
            gender = form.gender.data
            email = form.email.data
            location = form.location.data
            bio = form.bio.data
            file = request.files['image']
            image = secure_filename(file.filename)
            created_on = datetime.now().strftime("%a %d %b %Y")
            file.save(os.path.join("app/static/images", image))
            user = UserProfile(uid, firstname, lastname, gender, email,
                               location, bio, image, created_on)
            db.session.add(user)
            db.session.commit()
            flash('USER CREATED SUCESSFULLY', 'success')
            return redirect(url_for('createuser', error=error))
    flash_errors(form)
    return render_template('createuser.html', form=form, error=error)
Exemplo n.º 8
0
def createUser():
    createUserForm = CreateUserForm(request.form)

    if request.method == 'POST' and createUserForm.validate():
        print('SimpleApp Ln 115')
        usersDict = {}
        db = shelve.open('storage.db', 'c')
        try:
            print('SimpleApp Ln 119')
            usersDict = db['Users']
        except IOError:
            print("IOError")
        except:
            print("Error in retrieving Users from storage.db.")
        finally:
            user = User.User(createUserForm.firstName.data,
                             createUserForm.lastName.data,
                             createUserForm.DOB.data,
                             createUserForm.gender.data,
                             createUserForm.email.data, createUserForm.pw.data,
                             createUserForm.confirmpw.data)
            usersDict[user.get_email()] = user
            db['Users'] = usersDict
            db.close()

        return redirect(url_for('home'))
    return render_template('createUser.html', form=createUserForm)
Exemplo n.º 9
0
def show_user_form():
    """ Show form to create a user """
    if session.get('username'):
        return redirect(f"/users/{session.get('username')}")

    form = CreateUserForm()

    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        email = form.email.data
        first_name = form.first_name.data
        last_name = form.last_name.data

        new_user = User.register(username, password, email, first_name,
                                 last_name)
        db.session.add(new_user)
        db.session.commit()

        session['username'] = new_user.username

        return redirect(f"/users/{username}")

    else:
        return render_template('user_form.html', form=form)
Exemplo n.º 10
0
def signup():
    form = CreateUserForm()
    if request.method == 'POST' and form.validate():
        #generate user id
        userid = createID()
        
        #gets today's date
        profile_add_on = timeinfo()
        
        #creating confirmaton code
        ccode = form.email.data[:3]+userid
        
        #creating a default user photo 
        defaultimg = 'img/'+userid+'.png'
        shutil.copyfile(UPLOAD_FOLDER+'noprofileimage.png', UPLOAD_FOLDER+userid+'.png')
        
        # Saving profile to database and setting to inactive
        user = Profiles(userid=userid, password=form.password.data, email=form.email.data, \
                        profile_add_on=profile_add_on, code=ccode, highscore1=0, highscore2=0, tdollars=0, image=defaultimg)
              
        db.session.add(user)
        db.session.commit()
        
        # sending confirmation email
        sendcode(form.email.data, ccode)
        
        flash('Please complete registration by verifying your email')
        return render_template('signup.html', form=form)
    else:
        return render_template('signup.html', form=form)
Exemplo n.º 11
0
def register():
    form = CreateUserForm()
    if form.validate_on_submit():

        if not User.query.filter_by(email=form.email.data).first() == None:
            flash("This email account has already been registered in our database.")
            return redirect(url_for("register"))
            
        hash_password = generate_password_hash(
                            password=form.password.data,
                            method="pbkdf2:sha256",
                            salt_length=8
                        )

        new_user = User(
            email = form.email.data,
            password = hash_password,
            name = form.name.data
        )
        
        db.session.add(new_user)
        db.session.commit()
        login_user(new_user)

        return redirect(url_for("get_all_posts"))
    return render_template("register.html", form=form)
Exemplo n.º 12
0
def registration():
    """show register user form on GET request and handle form submit on POST request"""
    if 'username' not in session:
        form = CreateUserForm()
        if form.validate_on_submit():
            username = form.username.data
            password = form.password.data
            email = form.email.data
            first_name = form.first_name.data
            last_name = form.last_name.data
            new_user = User.register(username, password, email, first_name,
                                     last_name)
            db.session.add(new_user)
            try:
                db.session.commit()
            except IntegrityError:
                form.username.errors.append('Username Taken')
                return render_template('register.html', form=form)
            session['username'] = new_user.username
            flash('Welcome! Successfully created your account!', 'success')
            return redirect(f'/users/{username}')

        return render_template('register.html', form=form)

    username = session['username']
    return redirect(f'/users/{username}')
Exemplo n.º 13
0
def landing():
    if request.authorization:
        return redirect(url_for('.home'))
    form = CreateUserForm()
    if form.validate_on_submit():
        u = User(form.name.data, form.password.data, form.email.data)
        session.add(u)
        session.commit()
        return redirect(url_for('.home'))
    return render_template('landing.html', form=form)
Exemplo n.º 14
0
def add_user(request):
	if request.POST:
		form = CreateUserForm(request.POST)
		if form.is_valid():
			username = form.cleaned_data['username']
			password = form.cleaned_data['password1']
			user = User.objects.create_user(username)
			user.set_password(password)
			user.save()
			messages.add_message(request, messages.INFO, "User . "+username+" Addeded Sucessfully")
			return HttpResponseRedirect(reverse('dashboard'))
	else:
		form = CreateUserForm()
	base_template = 'dashboard.html'
	return render(request,'fileupload/add_user.html',{'form':form, 'base_template':base_template })
Exemplo n.º 15
0
def register(request):
    next = request.REQUEST.get('next', '')
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            UserProfile.objects.create(user=new_user)
            new_user = authenticate(username=new_user.username, password=request.POST['password1'])
            print new_user
            if new_user is not None and new_user.is_active:
                login(request, new_user)
            return HttpResponseRedirect(request.POST['next'])
    else:
        form = CreateUserForm()
    return render_to_response("registration/register.html", locals(), context_instance=RequestContext(request))
Exemplo n.º 16
0
def newUser():
    form = CreateUserForm()

    if form.validate_on_submit():
        if form.accountType.data != 'a' or form.accountType.data != 'p' or form.accountType.data != 's':
            db.session.add(
                User(form.email.data, form.password.data,
                     form.accountType.data))
            db.session.commit()
            app.logger.info("New User " + form.email.data + " registered")
            return redirect(url_for('dashboard'))

        return redirect(url_for('error'))

    return render_template('newUser.html', form=form)
def createuser():
	form = CreateUserForm()
	user = form.createuser.data
	createdb_choice = form.select_options.data
	if not user:
		return flask.render_template('querydetails.html',form = form)
	else:
		Query = "CREATE USER " + user + ' ' + createdb_choice + ';'
		try:
			if form.validate_on_submit():
				db.engine.execute(Query)
				flash("User Creation Successfull!")
				return flask.render_template('querydetails.html',form = form)
		except Exception:
			flash("Something Wrong With The Create User Query")
			return flask.render_template('querydetails.html',form = form)
Exemplo n.º 18
0
def user_create():
    if not current_user.is_anonymous:
        redirect(url_for('index'))

    form = CreateUserForm(request.form)

    if form.validate_on_submit():

        Cliente.create(
            username=form.username.data,
            password=form.password.data
        )

        return u'Usuario: {} creado con éxito'.format(form.username.data)

    return render_template('create_user.html', form=form)
Exemplo n.º 19
0
def registration_form():
    """Show and handle user registration form"""

    form = CreateUserForm()

    if form.validate_on_submit():
        current_user = User.register(form.username.data, form.password.data,
                                     form.email.data, form.first_name.data,
                                     form.last_name.data)
        db.session.add(current_user)
        db.session.commit()
        session["username"] = current_user.username
        return redirect(f'/users/{current_user.username}', code=302)

    else:
        return render_template('register_form.html', form=form)
Exemplo n.º 20
0
def createuser():
    form = CreateUserForm()
    if request.method == "POST":
        # change this to actually validate the entire form submission
        # and not just one field

        uid = random.randint(1, 1000)
        firstname = form.firstname.data
        lastname = form.lastname.data
        age = form.age.data
        gender = form.gender.data
        bio = form.bio.data
        username = form.username.data
        password = form.password.data
        file = request.files['image']
        image = secure_filename(file.filename)
        created_on = datetime.now().strftime("%a, %d %b %Y")
        file.save(os.path.join("app/static/images", image))
        user = UserProfile(uid, firstname, lastname, age, gender, bio,
                           username, password, image, created_on)
        db.session.add(user)
        db.session.commit()

        flash('USER CREATED SUCESSFULLY', 'success')

        return redirect(url_for('createuser'))

    flash_errors(form)
    return render_template('createuser.html', form=form)
Exemplo n.º 21
0
def admin_create():
    if request.method == 'POST':
        form = CreateUserForm()
        username = form.username.data
        password = form.password.data
        create = CreateUser()
        create.create_admin(username, password)
        return redirect('admin')
Exemplo n.º 22
0
def createuser(request):
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            firstname = form.cleaned_data['firstname']
            lastname = form.cleaned_data['lastname']
            email = form.cleaned_data['email']
            username = form.cleaned_data['username'].lower()
            password = form.cleaned_data['password']
            if User.objects.filter(username=username).exists():
                return HttpResponse('User %s already exists' % username)
            User.objects.create_user(username, email, password, first_name=firstname, last_name=lastname)
            return HttpResponse('User %s Created<br /><a href="/auth/">return</a>' % username)
    else:
        form = CreateUserForm()
        context = {'form':form}
        return render(request, 'auth/createuser.html', context)
Exemplo n.º 23
0
def add_user_fancy(request):
	if request.POST:
		form = CreateUserForm(request.POST)
		if form.is_valid():
			username = form.cleaned_data['username']
			password = form.cleaned_data['password1']
			user = User.objects.create_user(username)
			user.set_password(password)
			user.save()
			form = CreateUserForm()
			base_template = 'fancy.html'
			return render(request,'fileupload/add_user_fancy.html',
			{'form':form, 'base_template':base_template ,'message':"User "+user.username+" Added Sucessfully"})
	else:
		form = CreateUserForm()
	base_template = 'fancy.html'
	return render(request,'fileupload/add_user_fancy.html',{'form':form, 'base_template':base_template })
Exemplo n.º 24
0
def signup():

	form = CreateUserForm()

	if form.validate_on_submit():
		user = User(username=form.username.data,
					email=form.email.data,
					password=form.password.data)

		db.session.add(user)
		db.session.commit()

		login_user(user, remember=True)

		return redirect(url_for(users.index))

	return render_template('users/signup.html', form=form)
Exemplo n.º 25
0
def register():
    global is_admin
    user_form = CreateUserForm()
    if user_form.validate_on_submit():
        name = user_form.name.data
        email = user_form.email.data
        password = generate_password_hash(user_form.password.data, method='pbkdf2:sha256', salt_length=8)
        new_user = User(
            name=name,
            email=email,
            password=password
        )
        db.session.add(new_user)
        db.session.commit()
        login_user(new_user)
        if new_user.id == 1:
            is_admin = True
    return render_template("register.html", form=user_form)
Exemplo n.º 26
0
def create():
    if REGISTRATION == REGISTRATION_OPEN:
        form = CreateUserForm()
        if form.validate_on_submit():
            new_user = User(username=form.username.data,
                email=form.email.data,
                password=pbkdf2_sha256.encrypt(form.password.data))
            new_user.put()
            return redirect(url_for('panel'))
            #else:
            #    flash('Invalid details. Please try again.')
            #    redirect(url_for('create'))
        return render_template('users/create.html',
            title='Create account',
            form=form)
    else:
        return render_template('users/closed.html',
            title='Registration closed.')
Exemplo n.º 27
0
def create_user(request, activate_key):
    try:
        key = ActivateKey.objects.get(activate_key=activate_key, activated=False)
    except ActivateKey.DoesNotExist:
        raise Http404()
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            u = form.save(commit=False)
            u.set_password(form.cleaned_data.get('password'))
            u.save()
            key.activated = True
            key.save()
            set_snsuser_message(request,
                _(u"Create Your account. You can logged in now."))
            return HttpResponseRedirect(reverse('index'))
    else:
        form = CreateUserForm(initial={'email': key.belongs_to_email})
    return render_to_response('snsuser/snsuser_form.html', context_instance=RequestContext(request, {'form': form}))
Exemplo n.º 28
0
def user_create():
    if not current_user.is_anonymous:
        return redirect(url_for('index'))

    form = CreateUserForm(request.form)
    if form.validate_on_submit():
        try:
            user = Cliente.get(Cliente.nombre == form.username.data)
            if user:
                return render_template('create_user.html', form=form, error=u'nombre de usuario ya existente en sistema')
        except:
            Cliente.create(
                nombre=form.username.data,
                password=form.password.data,
                fechaInscripcion=datetime.now()
            )
            return render_template('create_user_success.html', username=form.username.data)

    return render_template('create_user.html', form=form)
Exemplo n.º 29
0
def register():
    form = CreateUserForm()
    if form.validate_on_submit():
        if Users.query.filter_by(email=form.email.data).first():
            flash("You have already registered. Please login instead.")
            return redirect(url_for("login"))
        else:
            user_hash = generate_password_hash(form.password.data,
                                               method='pbkdf2:sha256',
                                               salt_length=8)

            new_user = Users(email=form.email.data,
                             password=user_hash,
                             name=form.name.data)
            db.session.add(new_user)
            db.session.commit()
            login_user(new_user)
            return redirect(url_for('get_all_posts'))
    return render_template("register.html", form=form)
Exemplo n.º 30
0
def user_login():
    print current_user.is_anonymous

    if not current_user.is_anonymous:
        redirect(url_for('index'))
	
    form = CreateUserForm(request.form)
    if form.validate_on_submit():
        try:
            user = Cliente.get(username = form.username.data,
                password = form.password.data)
            print dir(user)
            print type(user)
            print user.is_anonymous
            login_user(user)
            return redirect(url_for('index'))
        except:
            return u'Usuario o contraseña inválida'

    return render_template('login.html', form=form)
Exemplo n.º 31
0
def admin():
    form = CreateUserForm()
    username = current_user.username
    info = db.users.find_one({"username": username})
    permissions = info['permissions']
    if request.method == 'GET':
        datas = db.users.find()
        return render_template('profile.html',
                               datas=datas,
                               form=form,
                               permissions=permissions)
Exemplo n.º 32
0
    def post(self, request, *args, **kwargs):
        form = CreateUserForm(request.POST)
        if form.is_valid():
            user = User(username=form.cleaned_data['username'])
            user.set_password(form.cleaned_data['password'])
            user.is_staff = (form.cleaned_data['user_role'] == 'dealer')
            user.is_active = True
            user.save()

            user_profile = UserProfile()
            user_profile.user = user
            user_profile.notes = form.cleaned_data['notes']
            user_profile.comission = form.cleaned_data['comission']
            if not user.is_staff:
                dealer = User.objects.get(
                    pk=form.cleaned_data['select_dealer'])
                user_profile.dealer = dealer
                user_profile.open_password = form.cleaned_data['password']
            user_profile.save()

        return HttpResponseRedirect('/user_list.html')
Exemplo n.º 33
0
def register():
    register_form = CreateUserForm()
    if register_form.validate_on_submit():

        if User.query.filter_by(email=register_form.email.data).first():
            # Send flash messsage
            flash("You've already signed up with that email, log in instead!")
            # Redirect to /login route.
            return redirect(url_for('login'))
        hashed_password = generate_password_hash(request.form.get('password'),
                                                 method='pbkdf2:sha256',
                                                 salt_length=8)
        new_user = User(email=request.form.get('email'),
                        name=request.form.get('name'),
                        password=hashed_password)
        db.session.add(new_user)
        db.session.commit()
        return redirect(url_for('get_all_posts'))
    return render_template("register.html",
                           form=register_form,
                           current_user=current_user)
Exemplo n.º 34
0
def createUser():
    createUserForm = CreateUserForm(request.form)

    if request.method == 'POST' and createUserForm.validate():
        usersDict = {}
        db = shelve.open('storage.db', 'c')
        try:
            usersDict = db['Users']
        except:
            print("Error in retrieving Users from storage.db.")
            user = User.User(createUserForm.firstName.data,
                             createUserForm.lastName.data,
                             createUserForm.membership.data,
                             createUserForm.gender.data,
                             createUserForm.remarks.data)
            usersDict[user.get_userID()] = user
            db['Users'] = usersDict
            db.close()
            return redirect(url_for('retrieveUsers'))
        return redirect(url_for('home'))
    return render_template('createUser.html', form=createUserForm)
Exemplo n.º 35
0
def register():
    users = User.query.all()
    form = CreateUserForm()
    if form.validate_on_submit():
        for user in users:
            if user.email == form.email.data:
                flash(
                    "The email you entered already exists, please enter it again"
                )
                return redirect(url_for("register"))
        new_user = User(
            email=form.email.data,
            password=generate_password_hash(form.password.data),
            name=form.name.data,
        )
        db.session.add(new_user)
        db.session.commit()
        login_user(new_user)
        return redirect(
            url_for("get_all_posts", logged_in=current_user.is_authenticated))
    return render_template("register.html", form=form)
Exemplo n.º 36
0
def sign_up(request):
	context = {}
	context['form'] = CreateUserForm()

	if request.method == 'POST':
		form = CreateUserForm(request.POST)
		context['form'] == form
		if  form.is_valid():
			username = form.cleaned_data['username']
			password = form.cleaned_data['password']
			email = form.cleaned_data['email']
			#print username
			new_user = User.objects.create_user(username=username, password=password)
			new_user.save()
			
			auth_user = authenticate(username=username, password=password)
			login(request, auth_user)

			return redirect('/countrylist/')

	return render(request, 'sign_up.html', context)
Exemplo n.º 37
0
def createUser(request):
    if request.method == 'POST':
        form =CreateUserForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            email = form.cleaned_data["email"]
            first_name = form.cleaned_data["first_name"]
            last_name = form.cleaned_data["last_name"]

            user = User.objects.create_user(username, email, password)
            user.first_name = first_name
            user.last_name = last_name

            user.save()

            return HttpResponseRedirect("/yaas/loginuser/")
    else:
        form =CreateUserForm()

    return render_to_response("newUser.html", {'form': form},context_instance= RequestContext(request))
Exemplo n.º 38
0
def create_user():
    form = CreateUserForm()
    if form.validate_on_submit():
        valid = True
        users = application.config['auth_domain'].get_users()
        if (form.username.data in [user.username for user in users]):
            form.username.errors.append("Username is not unique.")
            valid = False
        if (form.email.data in [user.email for user in users]):
            valid = False
            # TODO: handle this
        if (valid):
            username = form.username.data
            email = form.email.data
            password = form.password.data
            application.config['auth_domain'].add_user(username, email,
                                                       password)
            return redirect(url_for('accounts.get_login_form'))
    else:
        return render_template("create_user.html",
                               title="Create Account",
                               form=form)
Exemplo n.º 39
0
def submit_register_form():
    """Submits the user registration form."""

    form = CreateUserForm()

    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        email = form.email.data
        first_name = form.first_name.data
        last_name = form.last_name.data

        new_user = User.register(username, password, email, 
                                 first_name, last_name)

        db.session.add(new_user)
        db.session.commit()
        session["username"] = new_user.username

        return redirect(f"/users/{new_user.username}")
    else:
        return render_template('register.html', form=form)
Exemplo n.º 40
0
def createUser(request):
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            email = form.cleaned_data["email"]
            first_name = form.cleaned_data["first_name"]
            last_name = form.cleaned_data["last_name"]

            user = User.objects.create_user(username, email, password)
            user.first_name = first_name
            user.last_name = last_name

            user.save()

            return HttpResponseRedirect("/yaas/loginuser/")
    else:
        form = CreateUserForm()

    return render_to_response("newUser.html", {'form': form},
                              context_instance=RequestContext(request))
Exemplo n.º 41
0
def resolve(request):
    def _extract(d, keys):
        return dict((k, d[k]) for k in keys if k in d)

    workflow = get_workflow(request)

    if not workflow.is_authenticated():
        return redirect("/")

    if request.user.is_authenticated():
        workflow.associate_user(request, request.user)
        return login_ok_redirect()

    create_user_form = CreateUserForm(request.POST or None, initial=workflow.get_session().me())
    login_form = AuthenticationForm(request, request.POST or None)

    if create_user_form.is_valid():
        workflow.create_user(
            request,
            **(_extract(create_user_form.cleaned_data, [
                'username',
                'password',
                'first_name',
                'last_name',
                'email'])))
        return login_ok_redirect()
    
    elif login_form.is_valid():
        user = authenticate(username=login_form.cleaned_data['username'], password=login_form.cleaned_data['password'])
        if user and user.is_active:
            workflow.associate_user(request, user)
            login(request, user)
            return login_ok_redirect()
    
    else:
        request.session.set_test_cookie()

    return render(request, "resolve/resolve.html", dict(create_user_form=create_user_form, login_form=login_form))
Exemplo n.º 42
0
def create_user():
    if not g.user.is_admin():
        logger.error("%s tried to access /create-user", g.user.email, id)
        abort(403)
    form = CreateUserForm()

    if form.validate_on_submit():
        if request.form['button'] == 'Cancel':
            return form.redirect(url_for('user_list'))
        user = User(email=form.email2.data,
                    password=form.pass2.data,
                    name=form.name.data)

        db.session.add(user)
        db.session.commit()

        flash("User successfully created")
        logger.info("%s was registered", user.email)
        return redirect(url_for('user_list'))

    return render_template('admin_register.html',
                           title="Create a new user",
                           form=form)
Exemplo n.º 43
0
def create_user():
    if not g.user.is_admin():
        logger.error("%s tried to access /create-user", g.user.email, id)
        abort(403)
    form = CreateUserForm()

    if form.validate_on_submit():
        if request.form['button'] == 'Cancel':
            return form.redirect(url_for('user_list'))
        user = User(email = form.email2.data,
                    password = form.pass2.data,
                    name = form.name.data)

        db.session.add(user)
        db.session.commit()

        flash("User successfully created")
        logger.info("%s was registered", user.email)
        return redirect(url_for('user_list'))

    return render_template('admin_register.html',
            title = "Create a new user",
            form = form)
Exemplo n.º 44
0
def create(request):
    """
    show a form for user registration
    """
    if request.method == 'POST':
        # arriving data to process
        form = CreateUserForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            
            if data['password1'] != data['password2']:
                return django.shortcuts.render_to_response('create_form.html',
                                                   {'form': form, 'error_message': 'The two versions of your password differed!'},
                                                   context_instance=django.template.RequestContext(request))
            
            hashed_password = django.contrib.auth.hashers.make_password(data['password1'])
            user = django.contrib.auth.models.User(username=data['nick'],
                                                   first_name=data['firstname'],
                                                   last_name=data['lastname'],
                                                   email=data['email'],
                                                   password=hashed_password)
            user.save()
            user.userprofile.sex = data['sex']
            user.userprofile.save()
            
            return django.shortcuts.redirect('homepage.views.home') # todo: redirect to the login page
        else:
            return django.shortcuts.render_to_response('create_form.html',
                                                   {'form': form, 'error_message': 'Input invalid.'},
                                                   context_instance=django.template.RequestContext(request))
    else:
        # show an empty form 
        form = CreateUserForm()
        return django.shortcuts.render_to_response('create_form.html',
                                                   {'form': form},
                                                   context_instance=django.template.RequestContext(request))
Exemplo n.º 45
0
def admin_user():

    create_form = CreateUserForm()
    create_form.roles.query = Role.query.all()

    delete_form = DeleteUserForm()
    delete_form.users.query = User.query.all()

    update_form = UpdateUserForm()
    update_form.users.query = User.query.all()
    update_form.roles.query = Role.query.all()

    if request.method == 'POST':
        if create_form.data['create'] and create_form.validate():
            form = create_form
            user = User.query.filter_by(user_id=form.create_id.data).first()
            role = form.roles.data
            
            if user == None:
                user = User(
                    user_id=form.create_id.data,
                    user_name=form.create_name.data)
                user.password = '******'
                user.role = role

            db.session.add(user)
            db.session.commit()
            
            status = u'success'
            message = u'成功添加登录用户'
            session['message']=messages(status, message)
            return redirect(url_for('admin'))
        elif delete_form.data['delete'] and delete_form.validate():
            form = delete_form
            user = form.users.data
            
            db.session.delete(user)
            db.session.commit()
            
            status = u'warning'
            message = u'成功删除登录用户'
            session['message']=messages(status, message)
            return redirect(url_for('admin'))
        elif update_form.data['update'] and update_form.validate():
            form = update_form
            user = form.users.data
            role = form.roles.data
            name = form.update_name.data
            password = form.update_passwd.data
            user.role = role
            
            if password != '':
                user.password = password
            elif name != '':
                user.user_name = name
            
            db.session.add(user)
            db.session.commit()
            
            status = u'info'
            message = u'成功修改登录用户信息'
            session['message']=messages(status, message)
            return redirect(url_for('admin'))

    return render_template('admin-user.html', create_form=create_form, delete_form=delete_form, update_form=update_form)