Ejemplo n.º 1
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)
Ejemplo n.º 2
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
Ejemplo n.º 3
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
Ejemplo n.º 4
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
Ejemplo n.º 5
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
Ejemplo n.º 6
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'))
Ejemplo n.º 7
0
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
Ejemplo n.º 8
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, '*****@*****.**')
Ejemplo n.º 9
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, '*****@*****.**')
Ejemplo n.º 10
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)
Ejemplo n.º 11
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)
Ejemplo n.º 12
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)
Ejemplo n.º 13
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('/')
Ejemplo n.º 14
0
def create_profile(sender, **kw):
    user = kw["instance"]
    if kw["created"]:
        user_profile = UserProfile()
        user_profile.user = user
        user_profile.save()                
Ejemplo n.º 15
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."})