示例#1
0
文件: views.py 项目: zdimon/GameHub2
def subscribe(request,email,lesson_id,token):
    from django.shortcuts import redirect
    from django.contrib.auth import authenticate, login
    from django.http import HttpResponseRedirect
    uname = email.replace('--att--','@')
    uname = uname.replace('--dot--','.')
    lesson = Lesson.objects.get(pk=lesson_id)
    try:
        user = UserProfile.objects.get(username=uname)
    except:
        user = UserProfile()
        user.username = uname
        user.set_password('123')
        user.is_active = True
        user.email = uname
        user.save()
        
    user.backend = 'main.auth.ProfileUserModelBackend'
    login(request, user)
    try:
        Subscriber2Lesson.objects.get(lesson=lesson, user=user)
    except:
        u2l = Subscriber2Lesson()
        u2l.user = user
        u2l.lesson = lesson
        u2l.save()

    return redirect('my_profile')
示例#2
0
class TestSignupView(TestCase):
    def setUp(self) -> None:
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')
        self.user_profile = UserProfile()
        self.user_profile.user = self.user
        self.user_profile.save()

        self.team = Team(name='Kitchen', description='Cook stuff.', max_size=2)
        self.team.save()

        self.membership = TeamMembership(team=self.team,
                                         member=self.user)
        self.membership.save()

    def test_signup_form_validation(self):
        data = {
            'first_name': 'Foo',
            'last_name': 'Bar',
            'years_on_playa': 2,
            'invited_by': 'Baz Qux',
            'email': '*****@*****.**',
            'password': '******',
            'duplicate_password': '******',
            'phone': '555-555-5555',
            'zipcode': '12345',
            'g-recaptcha-response': 'PASSED',
            'interested_team': self.team.id,
        }
        os.environ['RECAPTCHA_TESTING'] = 'True'
        form = SignUpForm(data)
        self.assertTrue(form.is_valid())
示例#3
0
def registerUser(request):
    username = request.POST['username']
    password = request.POST['password']
    #retyped_password = request.POST['rpassword']
    email    = request.POST['email']

    #check to see that username doesn't already exist
    if User.objects.filter(username=username).exists():
        error = "username already exists"
        return render(request, 'homepage/registration.html', {"error":error})

    # check that passwords match and are >= 5 characters
    if len(password) < 7:
        error = "password must be at least 7 characters long"
        return render(request, 'homepage/registration.html', {"error": error})

    else: #create a user and log them in
        #User Profile Object
        newUser = UserProfile(username=username, points=0)
        newUser.save()
        #django user
        User.objects.create_user(username, email, password)
        user = authenticate(username=username, password=password)
        login(request, user)
        return redirect('main/')
示例#4
0
 def save(self, commit=True):
     user = super(RegistrationForm, self).save(commit=True)
     user = UserProfile(user=user,
                        birth_day=self.cleaned_data['birth_day'],
                        phone=self.cleaned_data['phone'])
     user.save()
     return user
示例#5
0
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password1']

            salt = sha.new(str(random.random())).hexdigest()[:5]
            activation_key = sha.new(salt+username).hexdigest()
            key_expires = datetime.datetime.today() + datetime.timedelta(2)

            user = User.objects.create_user(username, email, password)
            user.is_active = False
            user.save()

            user_profile = UserProfile(user=user, activation_key=activation_key, key_expires=key_expires)
            user_profile.save()
    
            email_subject = "PartyMaker EMail Bestätigung"
            email_text = "Hallo %s,\n du hast dich bei Party Maker regierstriert. Klicke auf den folgenden\
                Link um deinen Account zu aktivieren.\n http://localhost:8000/validate/%s\n mfG das PartyMaker Team" % (
                    username, activation_key)
            email_address=settings.REGISTRATION_EMAIL_ADDRESS
            send_mail(email_subject, email_text, email_address, [email])
            return HttpResponseRedirect('thanks')
    else: 
         form = RegistrationForm()
    return render_to_response('register.xhtml', {'form':form},  context_instance=RequestContext(request)) 
示例#6
0
def request_database_add_personal_details(request):
    constraint = helpers.constraint(request, "POST");
    data = constraint.safe({
        "first_name": True,
        "last_name": True,
        "department": False
    });

    request.user.first_name = data['first_name'];
    request.user.last_name = data['last_name'];
    request.user.full_clean();
    request.user.clean();
    request.user.save();

    try:
        of_department = Department.objects.get(id=data['department']);

        of_user_profile = UserProfile(
            user=request.user,
            department= of_department
        );

        of_user_profile.full_clean();
        of_user_profile.clean();
        of_user_profile.save();

        return redirect("/");

    except Department.DoesNotExist:
        raise Department.DoesNotExist("Index id of department object does not exists");

    pass;
示例#7
0
def mainpage(request):
    #FIX TO REDIRECT
    context = RequestContext(request)
    if request.user.is_authenticated():
         return HttpResponseRedirect('/main/userpage/')
    else:
        if request.method == 'POST':
            user_form = UserForm(data=request.POST)
            if user_form.is_valid() and (request.POST['password'] == request.POST['check']):
                user = user_form.save()
                user.set_password(user.password)
                user.save()
                userprofile = UserProfile()
                userprofile.user = user.username
                userprofile.email = user.email
                userprofile.joined = datetime.datetime.now()
                userprofile.save()

                user = authenticate(username=user_form.cleaned_data['username'],
                                    password=user_form.cleaned_data['password'],
                                    )
                login(request, user)

                return HttpResponseRedirect('/main/userpage/')

            else:
                print user_form.errors
        else:
            user_form = UserForm()



    return render_to_response('main/main.html',{'form': user_form,}, context)
示例#8
0
class TestSignupView(TestCase):
    def setUp(self) -> None:
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')
        self.user_profile = UserProfile()
        self.user_profile.user = self.user
        self.user_profile.save()

        self.team = Team(name='Kitchen', description='Cook stuff.', max_size=2)
        self.team.save()

        self.membership = TeamMembership(team=self.team, member=self.user)
        self.membership.save()

    def test_signup_form_validation(self):
        data = {
            'first_name': 'Foo',
            'last_name': 'Bar',
            'years_on_playa': 2,
            'invited_by': 'Baz Qux',
            'email': '*****@*****.**',
            'password': '******',
            'duplicate_password': '******',
            'phone': '555-555-5555',
            'zipcode': '12345',
            'g-recaptcha-response': 'PASSED',
            'interested_teams': [self.team.id],
        }
        os.environ['RECAPTCHA_TESTING'] = 'True'
        form = SignUpForm(data)
        self.assertTrue(form.is_valid())
def create_test_user(name=None):
    if not name: # pragma: no cover
        name = ''.join([random.choice(string.ascii_letters) for i in range(10)])
    user = User.objects.create_user(name, '*****@*****.**', name)
    prof = UserProfile(user=user, timezone='America/New_York', email_valid=True, grad_class=2016, 
        membership_status='CAN', location='New York City, NY')
    prof.save()
    return user
示例#10
0
 def create(self, validated_data):
     user = User(email=validated_data['email'],
                 username=validated_data['username'])
     user.set_password(validated_data['password'])
     user.save()
     user_profile = UserProfile(user=user)
     user_profile.save()
     return user
示例#11
0
def createNewUserProfile(user):
    profile = UserProfile()
    profile.user = user
    profile.username = user.username
    profile.first_name = user.first_name
    profile.last_name = user.last_name
    profile.save()
    return profile
示例#12
0
 def setUp(self):
     user = User.objects.create_user(username='******',
                                     email='*****@*****.**',
                                     password='******')
     user_profile = UserProfile()
     user_profile.user = user
     user_profile.save()
     self.user_profile = user_profile
示例#13
0
def run():
    User = get_user_model()

    #  Update the users in this list.
    #  Each tuple represents the username, password, email, firstname and lastname of a user.
    users = [
        ('user_1', 'phgzHpXcnJ', '*****@*****.**'),
        ('user_2', 'ktMmqKcpJw', '*****@*****.**'),
    ]

    for username, password, email in users:
        try:
            print('Creating user: '******'User ',username, ' successfully created.')

        except:
            print('There was a problem creating the user:'******'. Error: ', sys.exc_info()[1])

    data_user = [   ['user_1', 'Kees', 'van Kooten'],
                    ['user_2', 'Hoeren', 'Neuken'],
    ]

    user_all = User.objects.all()
    userprofile_all = UserProfile.objects.all()

    # for i in range(len(data_user)):
    #     does_exist = False
    #     for j in userprofile_all:
    #         if data_user[i][0] == j: 
    #             print('data_user_username: '******'userprofile_all: ', j)
    #             does_exist = True
       
    for i in range(len(user_all)):
        print(user_all[i])
        does_exist = False
        for j in userprofile_all:
            if user_all[i] == j: 
    #             print('data_user_username: '******'userprofile_all: ', j)
                does_exist = True

        if does_exist == False :

            for j in range(len(data_user)):
                if str(user_all[i]) == str(data_user[j][0]):
                    print('OK')
                    p = UserProfile(
                        user        =   user_all[i],
                        firstname   =   str(data_user[j][1]), 
                        lastname    =   str(data_user[j][2]), 
                    )
                    p.save()
示例#14
0
def oauth_authenticated(request):
    token = oauth.Token(
        request.session['request_token']['oauth_token'],
        request.session['request_token']['oauth_token_secret']
    )
    if 'oauth_verifier' in request.GET:
        token.set_verifier(request.GET['oauth_verifier'])
    client = oauth.Client(consumer, token)
    resp, content = client.request(access_token_url, "GET")
    if resp['status'] != '200':
        raise Exception("Invalid response from LinkedIn.")
    access_token = dict(cgi.parse_qsl(content))
    headers = {'x-li-format': 'json'}
    fields = [
        'id',
        'first-name',
        'last-name',
        'email-address',
    ]
    url = "http://api.linkedin.com/v1/people/~:(%s)" % ','.join(fields)
    token = oauth.Token(
        access_token['oauth_token'],
        access_token['oauth_token_secret']
    )
    client = oauth.Client(consumer, token)
    resp, content = client.request(url, "GET", headers=headers)
    profile = json.loads(content)
    # Step 3: lookup the user or create them if they don't exist.
    firstname = profile['firstName']
    lastname = profile['lastName']
    identifier = profile['id']
    email = profile['emailAddress']
    try:
        user = User.objects.get(username=identifier)
    except User.DoesNotExist:
        user = User.objects.create_user(
            identifier,
            email,
            access_token['oauth_token_secret']
        )
        user.first_name = firstname
        user.last_name = lastname
        user.save()
        # Save our permanent token and secret for later.
        userprofile = UserProfile()
        userprofile.user = user
        userprofile.oauth_token = access_token['oauth_token']
        userprofile.oauth_secret = access_token['oauth_token_secret']
        userprofile.save()
    # Authenticate the user and log them in using Django's pre-built
    # functions for these things.
    user = authenticate(
        username=identifier,
        password=access_token['oauth_token_secret']
    )
    login(request, user)
    return HttpResponseRedirect(reverse('home'))
示例#15
0
文件: forms.py 项目: TomCoder/formhub
 def save(self, new_user):
     new_profile = UserProfile(user=new_user, name=self.cleaned_data['name'],
             city=self.cleaned_data['city'],
             country=self.cleaned_data['country'],
             organization=self.cleaned_data['organization'],
             home_page=self.cleaned_data['home_page'],
             twitter=self.cleaned_data['twitter'])
     new_profile.save()
     return new_profile
示例#16
0
 def save(self, new_user):
     new_profile = \
         UserProfile(user=new_user, name=self.cleaned_data['name'],
                     city=self.cleaned_data['city'],
                     country=self.cleaned_data['country'],
                     organization=self.cleaned_data['organization'],
                     home_page=self.cleaned_data['home_page'],
                     twitter=self.cleaned_data['twitter'])
     new_profile.save()
     return new_profile
示例#17
0
def join(request):
    if request.method == 'POST':
        user = User.objects.create_user(request.POST.get('email'),request.POST.get('email'),request.POST.get('password'))
        user.first_name = request.POST.get('first_name')
        user.last_name = request.POST.get('last_name')
        user.save()
        user_profile = UserProfile (user=user)
        user_profile.save()
        if user is not None:
            request.session['user'] = user_profile
            return HttpResponseRedirect(reverse('main.views.dashboard'))
示例#18
0
class TestTeamView(TestCase):
    def setUp(self) -> None:
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')
        self.user_profile = UserProfile()
        self.user_profile.user = self.user
        self.user_profile.save()

        self.team = Team(name='Kitchen', description='Cook stuff')
        self.team.save()
示例#19
0
class TestTeamView(TestCase):
    def setUp(self) -> None:
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')
        self.user_profile = UserProfile()
        self.user_profile.user = self.user
        self.user_profile.save()

        self.team = Team(name='Kitchen', description='Cook stuff')
        self.team.save()
示例#20
0
 def save_user(self, request, sociallogin, form=None):
     user = DefaultSocialAccountAdapter.save_user(self,
                                                  request,
                                                  sociallogin,
                                                  form=form)
     if UserProfile.objects.filter(user=user).exists():
         pass
     else:
         new_user = UserProfile(user=user, name=user.get_full_name())
         new_user.save()
     # print("Inside the adapter")
     return redirect('/')
 def form_valid(self, form):
     new_user = form.save(commit=False)
     new_user.user = new_user
     new_user.first_name = form.cleaned_data['first_name']
     new_user.last_name = form.cleaned_data['last_name']
     new_user.is_staff = True
     new_user.save()
     new_restaurant = Restaurant(owner=new_user, name=form.cleaned_data['name'])
     new_restaurant.save()
     new_profile = UserProfile(user=new_user, owner=new_restaurant)
     new_profile.save()
     return super().form_valid(form)
示例#22
0
文件: methods.py 项目: mkapiczy/ZPR
def createNewUserProfile(user):
    try:
        profile = UserProfile.objects.get(user=user)
    except UserProfile.DoesNotExist:
        profile = UserProfile()
        profile.user = user
        profile.username = user.username
        profile.first_name = user.first_name
        profile.last_name = user.last_name
        profile.save()
        return profile
    return None
def add_user_task(sid, data):
    try:
        user = UserProfile.objects.get(login=data['login'])
    except ObjectDoesNotExist:
        print('No user')
        user = UserProfile()
        user.login = data['login']
        user.save()
    con = UserConnection()
    con.user = user
    con.sid = sid
    con.save()
    UserConnection.check_online(user)
 def form_valid(self, form):
     new_user = form.save(commit=False)
     new_user.user = new_user
     new_user.first_name = form.cleaned_data['first_name']
     new_user.last_name = form.cleaned_data['last_name']
     new_user.save()
     new_profile = UserProfile(user=new_user, number=form.cleaned_data['number'],
                               city=form.cleaned_data['city'],
                               zip_code=form.cleaned_data['zip_code'],
                               address=form.cleaned_data['address'],
                               allergies=form.cleaned_data['allergies'])
     new_profile.save()
     return super().form_valid(form)
示例#25
0
 def save(self, commit=True):
     user = User.objects.create_user(self.cleaned_data['username'], self.cleaned_data['email'],
                                     self.cleaned_data['password1'])
     user.first_name = self.cleaned_data['first_name']
     user.last_name = self.cleaned_data['last_name']
     user.groups.add(Group.objects.get(name="Volunteer"))
     user.save()
     profile = UserProfile(user=user)
     profile.timezone = self.cleaned_data['timezone']
     profile.grad_class = int(self.cleaned_data['grad_class'])
     profile.membership_status = self.cleaned_data['member_status']
     profile.save()
     return user
示例#26
0
def home_profile(request):
    user = request.user

    try:
        profile = user.get_profile()
    except UserProfile.DoesNotExist:
        profile = UserProfile(user=user)
        profile.save()

    attendships = user.attendships.order_by("date")
    for attendship in attendships:
        attendship.past = attendship.date < date.today()

    return render_to_response('main/home_profile.html', RequestContext(request, {'profile':profile, 'attendships':attendships}))
示例#27
0
    def save(self, commit=True):
        user = super(CustomUserCreationForm, self).save(commit=False)
        user.username = self.cleaned_data['username']
        if commit:
            user.save()

            try:
                profile = user.get_profile()
            except:
                profile = UserProfile(user=user)

            profile.save()

        return user
示例#28
0
 def save(self, commit=True):
     user = User.objects.create_user(self.cleaned_data['username'], self.cleaned_data['email'],
                                     self.cleaned_data['password1'])
     user.first_name = self.cleaned_data['first_name']
     user.last_name = self.cleaned_data['last_name']
     if self.cleaned_data.get('volunteer'):
         user.groups.add(Group.objects.get(name="Volunteer"))
     if self.cleaned_data.get('org_admin'):
         user.groups.add(Group.objects.get(name="Org_Admin"))
     user.save()
     profile = UserProfile(user=user)
     profile.timezone = self.cleaned_data['timezone']
     profile.save()
     return user
示例#29
0
def register(request):
    serializer = RegistrationSerializer(data=request.data)
    if serializer.is_valid():
        new_user = User.objects.create(
            username=serializer.validated_data.get('username'),
            password=make_password(serializer.validated_data.get('password')),
            first_name=serializer.validated_data.get('first_name'),
            last_name=serializer.validated_data.get('last_name'),
            email=serializer.validated_data.get('email'))
        new_user_profile = UserProfile(account=new_user)
        new_user_profile.save()
        return Response(status=status.HTTP_200_OK)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#30
0
    def handle(self, *args, **options):
        count = options["users"]

        users = []
        waiters = []
        managers = []

        _usernames = []
        # generate users
        for i in range(count):
            n = gen_unique_name(_usernames, ("user_" + "".join(random.sample(string.lowercase, 3)),))
            print "generate %d. user (%s)" % (i + 1, n)
            u = User()
            u.username = n
            u.password1 = "".join(random.sample(string.lowercase + string.digits, 10))
            u.password2 = u.password1
            users.append(u)
            u.save()
            # generate user roles
            # waiters
            if i % 20 == 1:
                ur = UserRole()
                ur.user = u
                ur.role = _roles[1]
                ur.restaurant = random.choice(Restaurant.objects.all())
                ur.save()
                print "marking %s as waiter" % u.username
                waiters.append(u)
                if u in users:
                    users.remove(u)
            # managers
            if i % 40 == 1:
                ur = UserRole()
                ur.user = u
                ur.role = _roles[0]
                ur.restaurant = random.choice(Restaurant.objects.all())
                ur.save()
                print "marking %s as manager" % u.username
                managers.append(u)
                if u in users:
                    users.remove(u)
            # every 2nd user a profile
            if i % 2 == 0:
                print "Adding user profile"
                profile = UserProfile()
                profile.user = u
                profile.save()

        self.stdout.write('Successfully added %d users' % count)
示例#31
0
    def setUp(self) -> None:
        user = User.objects.create_user(username='******',
                                        email='*****@*****.**',
                                        password='******')
        user_profile = UserProfile()
        user_profile.user = user
        user_profile.save()

        user2 = User.objects.create_user(username='******',
                                         email='*****@*****.**',
                                         password='******')
        user_profile2 = UserProfile()
        user_profile2.user = user2
        user_profile2.save()

        self.user_profile = user_profile
        self.user_profile2 = user_profile2
示例#32
0
    def post(self, request):
        form = SignUpForm(request.POST)
        if form.is_valid():

            checkuser=User.objects.filter(username=form.cleaned_data.get('username')).first()
            if checkuser:
                return redirect('/login/')


            userdata=dict(form.cleaned_data)
            profiledata=dict(form.cleaned_data)

            userdata.pop('phno')
            userdata.pop('dob')

            # user = User.objects.create_user(**form.cleaned_data)
            user = User.objects.create_user(**userdata)

            profiledata.pop('username')
            profiledata.pop('password')
            profiledata.pop('email')
            obj = User.objects.latest('id')


            profiledata['user_id']=obj.id

            profile=UserProfile(dob=profiledata['dob'],phno=profiledata['phno'],user_id=profiledata['user_id'])



            profile.save()


            user = authenticate(
                request,
                username = form.cleaned_data['username'],
                password = form.cleaned_data['password']
            )

            if user is not None:
                login(request, user)
                return redirect('/menu_index/')
            else:
                messages.error(request, 'Invalid Credentials')

            return redirect('/login/')
示例#33
0
def post(request: HttpRequest) -> HttpResponse:
    if request.method != 'POST':
        return redirect('signup')

    if settings.REGISTRATION_CLOSED:
        return redirect('registration-closed')

    form = SignUpForm(data=request.POST)
    if not form.is_valid():
        return render(request,
                      'registration/signup.html',
                      context={
                          'form': form,
                      })

    with transaction.atomic():
        try:
            User.objects.create_user(
                username=form.cleaned_data['email'],
                email=form.cleaned_data['email'],
                password=form.cleaned_data['password'],
                first_name=form.cleaned_data['first_name'],
                last_name=form.cleaned_data['last_name'])
        except IntegrityError as e:
            if str(e) == 'UNIQUE constraint failed: auth_user.username':
                return HttpResponseBadRequest('User already exists.')
            raise

        user = authenticate(username=form.cleaned_data['email'],
                            password=form.cleaned_data['password'])
        assert user is not None

        user_profile = UserProfile()
        user_profile.years_on_playa = form.cleaned_data['years_on_playa']
        user_profile.invited_by = form.cleaned_data['invited_by']
        user_profile.phone_number = form.cleaned_data['phone']
        user_profile.zipcode = form.cleaned_data['zipcode']
        user_profile.user = user
        user_profile.save()

        membership = TeamMembership(member=user,
                                    team=form.cleaned_data['interested_team'])
        membership.save()

        login(request, user)
        return redirect(user_profile)
示例#34
0
    def setUp(self) -> None:
        user = User.objects.create_user(username='******',
                                        email='*****@*****.**',
                                        password='******')
        user_profile = UserProfile()
        user_profile.user = user
        user_profile.save()

        user2 = User.objects.create_user(username='******',
                                         email='*****@*****.**',
                                         password='******')
        user_profile2 = UserProfile()
        user_profile2.user = user2
        user_profile2.save()

        self.user_profile = user_profile
        self.user_profile2 = user_profile2
示例#35
0
    def test_details(self):
        alice = User.objects.create_user('alice', '*****@*****.**', 'passwd')
        alice.save()

        profile = UserProfile(user=alice,
                              biography='Just a small-town girl...',
                              playa_name='Yoshi')
        profile.save()

        self.assertEqual(alice.profile, profile)
        self.assertEqual(set(alice.profile.food_restrictions.all()), set())

        vegan = FoodRestriction(name='Vegan', description='No animal products.')
        vegan.save()

        alice.profile.food_restrictions.add(vegan)
        alice.save()

        self.assertEqual(set(alice.profile.food_restrictions.all()), {vegan})
示例#36
0
文件: views.py 项目: zdimon/GameHub2
def enter(request,email,token):
    from django.shortcuts import redirect
    from django.contrib.auth import authenticate, login
    from django.http import HttpResponseRedirect
    uname = email.replace('--att--','@')
    uname = uname.replace('--dot--','.')
    try:
        user = User.objects.get(username=uname)
    except:
        user = UserProfile()
        user.username = uname
        user.set_password('123')
        user.is_active = True
        user.email = uname
        user.save()
        user = User.objects.get(username=uname)
    user.backend = 'main.auth.ProfileUserModelBackend'
    login(request, user)
    return redirect('lesson_for_student', id=1)
示例#37
0
def post(request: HttpRequest) -> HttpResponse:
    if request.method != 'POST':
        return redirect('signup')

    if settings.REGISTRATION_CLOSED:
        return redirect('registration-closed')

    form = SignUpForm(data=request.POST)
    if not form.is_valid():
        return render(request, 'registration/signup.html', context={
            'form': form,
        })

    with transaction.atomic():
        try:
            User.objects.create_user(username=form.cleaned_data['email'],
                                     email=form.cleaned_data['email'],
                                     password=form.cleaned_data['password'],
                                     first_name=form.cleaned_data['first_name'],
                                     last_name=form.cleaned_data['last_name'])
        except IntegrityError as e:
            if str(e) == 'UNIQUE constraint failed: auth_user.username':
                return HttpResponseBadRequest('User already exists.')
            raise

        user = authenticate(username=form.cleaned_data['email'],
                            password=form.cleaned_data['password'])
        assert user is not None

        user_profile = UserProfile()
        user_profile.years_on_playa = form.cleaned_data['years_on_playa']
        user_profile.invited_by = form.cleaned_data['invited_by']
        user_profile.phone_number = form.cleaned_data['phone']
        user_profile.zipcode = form.cleaned_data['zipcode']
        user_profile.user = user
        user_profile.save()

        membership = TeamMembership(member=user, team=form.cleaned_data['interested_team'])
        membership.save()

        login(request, user)
        return redirect(user_profile)
示例#38
0
    def test_details(self):
        alice = User.objects.create_user('alice', '*****@*****.**', 'passwd')
        alice.save()

        profile = UserProfile(user=alice,
                              biography='Just a small-town girl...',
                              playa_name='Yoshi')
        profile.save()

        self.assertEqual(alice.profile, profile)
        self.assertEqual(set(alice.profile.food_restrictions.all()), set())

        vegan = FoodRestriction(name='Vegan',
                                description='No animal products.')
        vegan.save()

        alice.profile.food_restrictions.add(vegan)
        alice.save()

        self.assertEqual(set(alice.profile.food_restrictions.all()), {vegan})
示例#39
0
def Registration(request):
    if request.user.is_authenticated():
            return HttpResponseRedirect('/profile/')
    if request.method == 'POST':
            form = UserCreateForm(request.POST)
            if form.is_valid():
                    user = User.objects.create_user(username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password1'])
                    user.save()
                    users = UserProfile(user=user, name=form.cleaned_data['name'], 
                        birthday=form.cleaned_data['birthday'], location=form.cleaned_data['location'], 
                        bio=form.cleaned_data['bio'], private=form.cleaned_data['private'])
                    users.save()
                    return redirect('LoginRequest')
            else:
                    return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request))
    else:
            ''' user is not submitting the form, show them a blank registration form '''
            form = UserCreateForm()
            context = {'form': form}
            return render_to_response('register.html', context, context_instance=RequestContext(request))
示例#40
0
def register_view(request):
    password = request.POST.get('newpassword')
    if password != request.POST.get('passcheck'):
        password = None
        return HttpResponse('passwords dont match! auth failed!')
    user = User()
    user.email = request.POST.get('email')
    user.username = user.email
    user.set_password(password)
    user.first_name = request.POST.get('first')
    user.last_name = request.POST.get('last')
    user.save()
    
    userProfile = UserProfile()
    userProfile.user = user
    userProfile.state = request.POST.get('state')
    userProfile.city = request.POST.get('city')
    userProfile.phone = request.POST.get('phone')
    userProfile.save()
    return redirect('/')
示例#41
0
def get_user_avatar(strategy, *args, **kwargs):
    user = kwargs['user']
    backend = kwargs['backend']
    response = kwargs['response']

    user_profile = None
    if not UserProfile.objects.filter(user=user).exists():
        user_profile = UserProfile(user=user)
    else:   # Already exists, just return.        
        return    

    if isinstance(backend, GoogleOAuth2):
        if response.get('image') and response['image'].get('url'):
            url = response['image'].get('url')
            ext = url.split('.')[-1]
            user_profile.avatar.save(
               '{0}.{1}'.format('avatar', ext),
               ContentFile(urllib2.urlopen(url).read()),
               save=False
            )
    user_profile.save()
示例#42
0
    def test_saving_and_retrieving_profiles(self):
        from django.contrib.auth.models import User
        u1 = User.objects.create(username='******')
        u2 = User.objects.create(username='******')

        profile1 = UserProfile()
        profile1.user = u1
        profile1.email = '*****@*****.**'
        profile1.save()

        profile2 = UserProfile()
        profile2.user = u2
        profile2.email = '*****@*****.**'
        profile2.save()

        saved_profiles = UserProfile.objects.all()
        self.assertEqual(saved_profiles.count(), 2)

        first_saved_profile = saved_profiles[0]
        second_saved_profile = saved_profiles[1]
        self.assertEqual(first_saved_profile.email, '*****@*****.**')
        self.assertEqual(second_saved_profile.email, '*****@*****.**')
示例#43
0
def populate():
    print "Creating Ramya"
    contact1 = Contacts(addr_line1="18570 NE 58th Ct, #K3084",
                        city="Redmond",
                        state="WA",
                        country="USA",
                        zipcode=98052,
                        email="*****@*****.**")
    contact1.save()
    user1 = UserProfile(first_name="Ramya", contact=contact1)
    user1.save()

    print "Creating Sanath"
    contact2 = Contacts(addr_line1="2 Arundel Road, #2",
                        city="Burlingame",
                        state="CA",
                        country="USA",
                        zipcode=94010,
                        email="*****@*****.**")
    contact2.save()
    user2 = UserProfile(first_name="Sanath", contact=contact2)
    user2.save()
示例#44
0
    def test_saving_and_retrieving_profiles(self):
        from django.contrib.auth.models import User
        u1 = User.objects.create(username = '******')
        u2 = User.objects.create(username = '******')
                
        profile1 = UserProfile()
        profile1.user = u1
        profile1.email = '*****@*****.**'
        profile1.save()

        profile2 = UserProfile()
        profile2.user = u2
        profile2.email = '*****@*****.**'
        profile2.save()

        saved_profiles = UserProfile.objects.all()
        self.assertEqual(saved_profiles.count(), 2)

        first_saved_profile = saved_profiles[0]
        second_saved_profile = saved_profiles[1]
        self.assertEqual(first_saved_profile.email, '*****@*****.**')
        self.assertEqual(second_saved_profile.email, '*****@*****.**')
示例#45
0
    def test_phone_number_parsing(self):
        alice = User.objects.create_user('alice', '*****@*****.**', 'passwd')
        alice.save()

        profile = UserProfile(user=alice,
                              biography='Just a small-town girl...',
                              playa_name='Yoshi')
        profile.save()

        test_cases = [
            '5555555555',
            '555-555-5555',
            '15555555555',
            '1-555-555-5555',
            '+15555555555',
            '+1-555-555-5555',
        ]

        for phone_number in test_cases:
            parsed_number = UserProfile.parse_phone_number(phone_number)
            assert len(parsed_number) == 12

        self.assertTrue(True)
示例#46
0
    def test_phone_number_parsing(self):
        alice = User.objects.create_user('alice', '*****@*****.**', 'passwd')
        alice.save()

        profile = UserProfile(user=alice,
                              biography='Just a small-town girl...',
                              playa_name='Yoshi')
        profile.save()

        test_cases = [
            '5555555555',
            '555-555-5555',
            '15555555555',
            '1-555-555-5555',
            '+15555555555',
            '+1-555-555-5555',
        ]

        for phone_number in test_cases:
            parsed_number = UserProfile.parse_phone_number(phone_number)
            assert len(parsed_number) == 12

        self.assertTrue(True)
示例#47
0
def register(request):
    if request.method == 'POST':
        formset = UserForm(request.POST, request.FILES)
        if formset.is_valid():
            newUser = User.objects.create_user(formset.data['username'], formset.data['email'],
                                               formset.data['password'])
            custom = UserProfile(user=newUser)
            custom.user_id = newUser.id
            custom.save()
            newUser = authenticate(username=request.POST['username'], password=request.POST['password'])
            login(request, newUser)
            d = {"user": request.user}
            return render_to_response("registration/register_success.html", d)
        else:
            d = {"formset": formset}
            d.update(csrf(request))
            return render_to_response("registration/register.html", d)

    else:
        userForm = UserForm()
        d = {"formset": userForm}
        d.update(csrf(request))
        return render_to_response("registration/register.html", d)
示例#48
0
文件: views.py 项目: jhelbert/coshare
def login_user(request):
	email = request.POST.get('email')
	password = request.POST.get('password')
	user = User.objects.get(email=email)

	if user.check_password(password):
		user.backend = 'django.contrib.auth.backends.ModelBackend'
		login(request,user)
		userprof = get_user_profile(request)
		if userprof is None:
			print "no userprof"
			if user.first_name:
				queue = Album(name=user.first_name + "'s Queue")
			else:
				queue = Album(name=user.username + "'s Queue")
			queue.save()
			userprof = UserProfile(user=user,queue=queue)
			userprof.save()


		return HttpResponseRedirect('/')
	else:
		return HttpResponseRedirect('/login/')
示例#49
0
 def register(self, request, **cleaned_data):
     def _get_first_last_names(name):
         name_split = name.split()
         first_name = name_split[0]
         last_name = u''
         if len(name_split) > 1:
             last_name = u' '.join(name_split[1:])
         return first_name, last_name
     new_user = \
         super(FHRegistrationView, self).register(request, **cleaned_data)
     new_profile = \
         UserProfile(user=new_user, name=cleaned_data['name'],
                     city=cleaned_data['city'],
                     country=cleaned_data['country'],
                     organization=cleaned_data['organization'],
                     home_page=cleaned_data['home_page'],
                     twitter=cleaned_data['twitter'])
     new_profile.save()
     if cleaned_data['name']:
         fn, ln = _get_first_last_names(cleaned_data['name'])
         new_user.first_name = fn
         new_user.last_name = ln
         new_user.save()
     return new_user
示例#50
0
文件: users.py 项目: bramlap/E-Choice
def run():
    User = get_user_model()

    #  Update the users in this list.
    #  Each tuple represents the username, password, email, firstname and lastname of a user.
    users = [
        ('alexanderbouma', '123qweasdzxc', '-'),
        ('student', '123qweasdzxc', '-'),
        ('teacher', '123qweasdzxc', '-'),
    ]

    for username, password, email in users:
        try:
            print('Creating user: '******'User ', username, ' successfully created.')

        except:
            print('There was a problem creating the user:'******'. Error: ',
                  sys.exc_info()[1])

    data_user = [
        ['bramlap', 'Bram', 'Lap'],
        ['alexanderbouma', 'Alexander', 'Bouma'],
        ['student', 'Student', 'Student'],
        ['teacher', 'Teacher', 'Teacher'],
    ]

    user_all = User.objects.all()
    userprofile_all = UserProfile.objects.all()

    for i in range(len(user_all)):
        does_exist = False
        for j in userprofile_all:
            if user_all[i] == j:
                does_exist = True

        if does_exist == False:

            for j in range(len(data_user)):
                if str(user_all[i]) == str(data_user[j][0]):
                    if str(user_all[i]) == 'teacher':
                        p = UserProfile(
                            user=user_all[i],
                            firstname=str(data_user[j][1]),
                            lastname=str(data_user[j][2]),
                            is_student=False,
                            is_teacher=True,
                        )
                        p.save()
                    else:
                        p = UserProfile(
                            user=user_all[i],
                            firstname=str(data_user[j][1]),
                            lastname=str(data_user[j][2]),
                        )
                        p.save()

                    print('OK')
示例#51
0
def create_user_profile(about='user_profile_about_test', group=None, user=None):
    group = group or create_group()
    user = user or create_user()
    user_profile = UserProfile(**locals())
    user_profile.save()
    return user_profile
示例#52
0
def add_event(request):
    '''
        The view that will be called when DA will add events from the WebPortal.
    '''

    if request.method == 'POST':

        try:
            user_id = str(request.META['HTTP_X_USER_ID'])
        except KeyError:
            return JsonResponse({
                "message": "Header missing: X-USER-ID",
                "status": 2
            })

        try:
            user_profile = UserProfile.objects.get(uuid=user_id)
            if not user_profile:
                raise Exception
        except Exception:
            return JsonResponse(
                {"message": "The given UserId doesnt correspond to any user."})
        ''' Add the below 2 lines on every page where DA functionalities are there. '''

        if not user_profile.is_da:
            return JsonResponse({
                "message": "You must be logged in as a DA to add events.",
                "status": 0
            })

        try:
            # just to decode JSON properly
            data = json.loads(request.body.decode('utf8').replace("'", '"'))
        except:
            return JsonResponse({
                "message": "Please check syntax of JSON data passed.",
                'status': 4
            })

        try:
            event_name = data['name']
            description = data['description']
            fund_goal = data['fund_goal']
            phone = data['phone']
            email = data['email']
        except KeyError as missing_data:
            return JsonResponse({
                "message":
                "Missing the following field: {}".format(missing_data),
                'status':
                2
            })

        try:
            int(data['fund_goal'])
        except:
            #phone numbers should be an integer or string only of numbers
            return JsonResponse({
                'status':
                0,
                'message':
                'Fund Goal has to be a positive integer.'
            })

        try:
            int(data['phone'])
        except:
            #phone numbers should be an integer or string only of numbers
            return JsonResponse({
                'status': 0,
                'message': 'Please enter a valid phone number.'
            })

        if len(phone) != 10:
            return JsonResponse({
                'status': 0,
                'message': 'Please enter a valid Phone Number.'
            })

        if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",
                        email):
            return JsonResponse({
                'status':
                0,
                'message':
                'Please enter a valid Email address.'
            })

        try:
            UserProfile.objects.get(email=email)
            return JsonResponse({
                'status':
                0,
                'message':
                'This Email has already been registered. PLease try some other email.'
            })
        except:
            pass

        try:
            profile = UserProfile()
            event_name = ' '.join(str(event_name).strip().split())
            name = 'Admin for Event: ' + event_name
            profile.name = name
            profile.email = str(email)
            profile.phone = int(phone)
            profile.emergency_phone = int(phone)
            profile.save()

            username = profile.name.split(':')[1] + str(profile.id)
            password = ''.join(choice(chars) for i in range(8))
            user = User.objects.create_user(username=username,
                                            password=password)
            profile.user = user
            profile.save()

            event = Event.objects.create(name=event_name,
                                         description=description,
                                         admin=profile,
                                         fund_goal=fund_goal)
            event.save()

            message = 'Event added Successfully!'
            return JsonResponse({'message': message, 'status': 1})

        except Exception as e:
            print(e)
            return JsonResponse({
                'message': 'Event could not be added. Please try again.',
                'status': 0
            })

    if request.method == 'GET':
        return JsonResponse({"message": "API for DA to add events."})
示例#53
0
def create_profile(sender, **kw):
    user = kw["instance"]
    if kw["created"]:
        user_profile = UserProfile()
        user_profile.user = user
        user_profile.save()                
示例#54
0
    def handle(self, *args, **options):
        conn = sqlite3.connect(options['userdb_path'][0])
        """
        CREATE TABLE users (
        0    login TEXT PRIMARY KEY, 
        1    firstname TEXT, 
        2    lastname TEXT, 
        3    email TEXT, 
        4    password TEXT,
        5    path TEXT,
        6    token TEXT, 
        7    accepted INTEGER,
        8    project TEXT,
        9    affiliation TEXT,
        10   ip TEXT,
        11   clearance TEXT,
        12   date TEXT,
        13   visit TEXT)
        """

        print("Migrating users table...")
        user_paths = {}

        for row in conn.execute('SELECT * FROM users;'):
            username = sanitize_username(row[0])
            password = "******" + row[4]
            email = row[3]
            is_active = True
            is_superuser = True if row[11] == 'admin' else False

            user_paths[row[5]] = username
            date_joined = datetime.strptime(
                row[12], "%Y-%m-%d").replace(tzinfo=timezone.utc)

            newuser = User(username=username,
                           password=password,
                           email=email,
                           is_active=is_active,
                           is_superuser=is_superuser,
                           is_staff=is_superuser,
                           date_joined=date_joined)
            newuser.save()

            fullname = "%s %s" % (row[1], row[2])
            institution = row[9]

            if len(fullname) < 2:
                fullname = None

            newuser_profile = UserProfile(user=newuser,
                                          fullname=fullname,
                                          orcid=None,
                                          institution=institution)
            newuser_profile.save()

        print(" - Successful.")
        print("Moving project files... ")

        for path in user_paths:
            username = user_paths[path]

            # old user project dir
            src = os.path.join(options['userfiles_path'][0], path)

            #new user project dir
            dst = os.path.join(settings.USER_DATA_DIR, username)

            try:
                shutil.copytree(src, dst)
            except FileNotFoundError:
                # if user path does not exists create empty dir for user
                os.makedirs(dst)

        print(" - Successful")
        print("Migratins project table... ")
        """
        CREATE TABLE projects (
        0    name TEXT PRIMARY KEY, 
        1    path TEXT, 
        2    user TEXT, 
        3    description TEXT)
        """
        for row in conn.execute('SELECT * FROM projects;'):
            name = row[0]
            slug = slugify(name).replace('-', '_')
            path = row[1]
            username = sanitize_username(row[2])
            description = row[3]

            #rename project files
            fileTypes_old = [
                'treeFile', 'dataFile', 'fastaFile', 'samplesOrderFile',
                'samplesInformationFile'
            ]
            fileTypes_new = [
                'tree.txt', 'data.txt', 'fasta.fa', 'samples-order.txt',
                'samples-info.txt'
            ]

            for i in range(5):
                try:
                    os.rename(
                        os.path.join(settings.USER_DATA_DIR, username, path,
                                     fileTypes_old[i]),
                        os.path.join(settings.USER_DATA_DIR, username, path,
                                     fileTypes_new[i]))
                except:
                    pass

            try:
                if not description or not len(description) > 0:
                    description = ""

                project = Project(name=name,
                                  slug=slug,
                                  user=User.objects.get(username=username),
                                  secret=path)

                samples_info = project.get_file_path('samples-order.txt',
                                                     default=None)
                samples_order = project.get_file_path('samples-info.txt',
                                                      default=None)

                if (samples_info
                        or samples_order) and not project.get_file_path(
                            'samples.db', default=None):
                    s = dbops.SamplesInformationDatabase(project.get_file_path(
                        'samples.db', dont_check_exists=True),
                                                         quiet=True)
                    s.create(samples_order, samples_info)

                interactive = project.get_interactive()

                # try to get number of leaves
                try:
                    leaves = get_names_order_from_newick_tree(
                        project.get_file_path('tree.txt', default=None))
                    project.num_leaves = len(leaves) if leaves != [''] else 0
                except:
                    project.num_leaves = 0

                # try to get number of layers
                try:
                    project.num_layers = len(
                        interactive.views['single']
                        [0]) - 1  # <- -1 because first column is contigs
                except:
                    project.num_layers = 0

                # store description
                dbops.update_description_in_db(
                    project.get_file_path('profile.db', default=None),
                    description or '')

                project.synchronize_num_states()
                project.synchronize_num_collections()

                project.save()

                # try to migrate old links.
                for row_links in conn.execute(
                        'SELECT * FROM views WHERE project LIKE \'%s\';' %
                    (name)):
                    old_link = OldLinks(
                        name=row_links[0],
                        user=sanitize_username(row_links[1]),
                        project=Project.objects.filter(
                            name=row_links[2],
                            user__username=sanitize_username(row_links[1]))[0],
                        is_public=True if row_links[3] == 1 else False,
                        token=row_links[4])
                    old_link.save()

                    project_link = ProjectLink(project=old_link.project,
                                               link=old_link.token)
                    project_link.save()

            except Exception as e:
                print(username + " " + name + " " + path +
                      " failed to create project, here is the exception " +
                      str(e))
                shutil.rmtree(
                    os.path.join(settings.USER_DATA_DIR, username, path))

        print(" - Successful")
示例#55
0
def register(request):

    if request.method == 'GET':
        return JsonResponse({
            'status':
            3,
            'message':
            'The API where new users can register themselves on the app.'
        })

    if request.method == 'POST':
        try:
            # just to decode JSON properly
            data = json.loads(request.body.decode('utf8').replace("'", '"'))
        except:
            return JsonResponse({
                "message": "Please check syntax of JSON data passed.",
                'status': 4
            })
        try:
            # see whether all fields passed in JSON or not
            data['name']
            data['email']
            data['phone']
            data['emergency_phone']
        except KeyError as missing_data:
            return JsonResponse({
                "message":
                "Missing the following field: {}".format(missing_data),
                'status':
                2
            })

        try:
            int(data['phone'])
        except:
            #phone numbers should be an integer or string only of numbers
            return JsonResponse({
                'status': 0,
                'message': 'Please enter a valid Phone Number.'
            })

        try:
            int(data['emergency_phone'])
        except:
            #phone numbers should be an integer or string only of numbers
            return JsonResponse({
                'status':
                0,
                'message':
                'Please enter a valid Emergency Phone Number.'
            })

        if len(data['phone']) != 10:
            return JsonResponse({
                'status': 0,
                'message': 'Please enter a valid Phone Number.'
            })
        if len(data['emergency_phone']) != 10:
            return JsonResponse({
                'status':
                0,
                'message':
                'Please enter a valid Emergency Phone Number.'
            })

        email = data['email']
        if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",
                        email):
            return JsonResponse({
                'status':
                0,
                'message':
                'Please enter a valid Email address.'
            })

        try:
            UserProfile.objects.get(email=email)
            return JsonResponse({
                'status':
                0,
                'message':
                'This Email has already been registered. Try some other email.'
            })
        except:
            pass
        try:
            profile = UserProfile()
            name = ' '.join(str(data['name']).strip().split())
            profile.name = name
            profile.email = str(data['email'])
            profile.phone = int(data['phone'])
            profile.emergency_phone = int(data['emergency_phone'])
            profile.save()

            #verify email
            send_to = profile.email
            body = email_body.register()
            email_token = utils.generate_email_token(profile)
            body = body % (
                name, str(request.build_absolute_uri(reverse("main:nill"))) +
                'email_confirm/' + email_token + '/')

            sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
            from_email = Email('*****@*****.**')
            to_email = Email(send_to)
            subject = "Email Confirmation for your account on Alertify app"
            content = Content('text/html', body)

            try:
                mail = Mail(from_email, subject, to_email, content)
                response = sg.client.mail.send.post(request_body=mail.get())
            except Exception:
                profile.delete()
                return JsonResponse({
                    'message': 'Error sending email. Please try again.',
                    'status': 0
                })

            message = "Registration successful! A confirmation link has been sent to %s. Kindly click on it to verify your email address." % (
                send_to)
            return JsonResponse({'message': message, 'status': 1})
        except Exception:
            return JsonResponse({
                'message': 'Registration failed due to unknown reasons.',
                'status': 0
            })