Esempio n. 1
0
def login(request):
    error = None
    notice = None
    # If form has been submitted
    if request.method == 'POST':
        form = LoginForm(request.POST)
        username = request.POST['username']
        password = request.POST['password']
        logging.info('Trying user %s authentication', username)
        user = authenticate(username=username, password=password)
        # Check if user correct
        if user is not None:
            django_login(request, user)
            logging.info("User %s logged in", user.username)
            
            if user.get_profile().is_administrator():
                cursor = connections['principal'].cursor()
                Region.fetch_all(cursor)
                cursor.close()
            return index(request)
        # If user is incorrect, error
        else:
            logging.error("User %s: bad credentials", username)
            request.flash['error'] = 'Nombre de usuario o contraseña incorrectos'
    # If it hasn't been submitted, display any pending notices
    else:   
        form = LoginForm()
    # If user couldn't access anywhere for any reason, return to login form
    return render_to_response('login.html', {
                'form': form,
            }, context_instance=RequestContext(request))
Esempio n. 2
0
def registration(request):
    '''
    A form to allow for registration of new users
    '''
    template_data = {}
    template_data.update(csrf(request))

    # Don't use captcha when registering through an app
    is_app = check_request_amazon(request) or check_request_android(request)
    FormClass = RegistrationFormNoCaptcha if is_app else RegistrationForm

    # Redirect regular users, in case they reached the registration page
    if request.user.is_authenticated() and not request.user.userprofile.is_temporary:
        return HttpResponseRedirect(reverse('core:dashboard'))

    if request.method == 'POST':
        form = FormClass(data=request.POST)

        # If the data is valid, log in and redirect
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            email = form.cleaned_data['email']
            user = Django_User.objects.create_user(username,
                                                   email,
                                                   password)
            user.save()

            # Pre-set some values of the user's profile
            language = Language.objects.get(short_name=translation.get_language())
            user.userprofile.notification_language = language

            # Set default gym, if needed
            gym_config = GymConfig.objects.get(pk=1)
            if gym_config.default_gym:
                user.userprofile.gym = gym_config.default_gym

                # Create gym user configuration object
                config = GymUserConfig()
                config.gym = gym_config.default_gym
                config.user = user
                config.save()

            user.userprofile.save()

            user = authenticate(username=username, password=password)
            django_login(request, user)
            messages.success(request, _('You were successfully registered'))
            return HttpResponseRedirect(reverse('core:dashboard'))
    else:
        form = FormClass()

    template_data['form'] = form
    template_data['title'] = _('Register')
    template_data['form_fields'] = [i for i in form]
    template_data['form_action'] = reverse('core:user:registration')
    template_data['submit_text'] = _('Register')
    template_data['extend_template'] = 'base.html'

    return render(request, 'form.html', template_data)
Esempio n. 3
0
def openid_get_identity(request, identity_url):
    """
    Select openid based on claim (identity_url).
    If none was claimed identity_url will be
    'http://specs.openid.net/auth/2.0/identifier_select'
    - in that case return default one
    - if user has no default one, return any
    - in other case return None!
    """

    for openid in request.user.openid_set.iterator():
        if identity_url == request.build_absolute_uri(
                reverse('openid-provider-identity', args=[openid.openid])):
            custom_log(request, "Found a valid OpenID identity: %s" % openid)
            return openid
    if identity_url == 'http://specs.openid.net/auth/2.0/identifier_select':
        # no claim was made, choose user default openid:
        openids = request.user.openid_set.filter(default=True)
        if openids.count() == 1:
            custom_log(request, "No claim was made. Chose ID %s" % openids[0])
            return openids[0]
        if request.user.openid_set.count() > 0:
            custom_log(request, "No claim was made. Chose ID %s" % request.user.openid_set.all()[0])
            return request.user.openid_set.all()[0]

    (user, _) = DjangoUser.objects.get_or_create(username=request.browser.user.username, defaults={"email": request.browser.user.email, "is_staff": False, "is_active": True, "is_superuser": False, "last_login": datetime.datetime.now(), "date_joined": datetime.datetime.now()})
    user.backend = 'django.contrib.auth.backends.ModelBackend' # Horrible hack.
    django_login(request, user)
    custom_log(request, "Creating new OpenID association for %s" % user.username, level="info")
    (openid, _) = OpenID.objects.get_or_create(user=user, openid=user.username)
    return openid
Esempio n. 4
0
def login(request):
    """
    The page a user can log in.
    """

    response = None
    context = {
        'data': None,
        'errors': None
    }
    login_form = LoginForm(request.POST)

    if request.method == 'POST':

        if login_form.is_valid():
            django_login(request, login_form.get_user())
            response = redirect('users:home')
        else:
            copy_global_error(login_form, 'login_failed', 'username_email')
            copy_global_error(login_form, 'not_validated', 'username_email')
            context.update({
                'data': login_form.data,
                'errors': login_form.errors
            })

    if not response:
        context['fields'] = login_form.fields
        return render(request, 'users/login.html', context)

    return response
Esempio n. 5
0
def login(request):
    logger.debug("in login")
    error_message = ''
    if request.method == 'POST':
        logger.debug("in login POST")
        form = Authentication_Form(request.POST)
        if form.is_valid():
            logger.debug(form.cleaned_data['email']+'<>'+form.cleaned_data['password'])
            user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password'])
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    return redirect('/vital')
                else:
                    form = User_Activation_Form(initial={'user_email': user.email})
                    return render(request, 'vital/user_registration_validate.html', {'message': 'User is not active. ' +
                                                                                        'Please check your mail(' +
                                                                                        user.email+') for ' +
                                                                                        'activation code',
                                                                             'form': form})
            else:
                error_message = 'Login failed! Check your username and password.'
        else:
            error_message = 'Login failed! Check your username and password.'
    else:
        form = Authentication_Form()
    return render(request, 'vital/login.html', {'form': form, 'error_message': error_message})
Esempio n. 6
0
def signup(request):
    """
    Muestra un formulario para registrar a un nuevo usuario y lo crea si la petición es POST
    :param request: HttpRequest
    :return: HttpResponse
    """
    success_message = []
    if request.method == "GET":
        form = SignupForm()
    else:
        form = SignupForm(request.POST)
        if form.is_valid():
            new_user = form.save()  # Guarda el objeto User y lo devuelve
            new_user = authenticate(username=request.POST["username"], password=request.POST["password1"])
            django_login(request, new_user)
            form = SignupForm()
            success_message = "<h4>¡El usuario se ha creado con éxito! --> "
            success_message += '<a href="{0}">'.format(reverse("posts_main"))
            success_message += "Entrar"
            success_message += "</a></h4>"
            success_message += "<hr>"
        else:
            form = SignupForm()
    context = {"form": form, "success_message": success_message}
    return render(request, "users/signup.html", context)
Esempio n. 7
0
def auth(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            email = request.POST.get('email')
            password = request.POST.get('password')
            # Redirect if OTP is set
            #if User.objects.get(email=email).OTP:
            #    messages.add_message(request, messages.ERROR, "OTP")
            #    return redirect('/login/')
            userId = User.objects.get(email=email).userId
            user = authenticate(userId=userId, password=password)
            if user:
                if user.is_active:
                    django_login(request, user)
                    # Redirect based on user account type
                    if user.is_staff or user.is_superuser:
                        return redirect('userAdmin')
                    else:
                        return redirect('activeRounds')
        # Access Denied
        messages.add_message(request, messages.ERROR, "Incorrect username or password")
        return redirect('/login/')
    else:
        return redirect('/login/')
Esempio n. 8
0
def login(request):
	"""
	Login View
	"""

	if(request.method == 'POST'):
		form =  LoginForm(data=request.POST)
		if form.is_valid():
			user = authenticate(email=request.POST['email'], password=request.POST['password'])
			if user is not None:
				if user.is_active:
					django_login(request, user)
					return redirect('/app/dashboard', request)
			else:
				form = LoginForm()
				return render_to_response('login.html', {
					'form' : form,
					'login_error_message' : 'Invalid Login Credentials',
				}, context_instance=RequestContext(request))
	else:
		form = LoginForm()

	return render_to_response('login.html', {
		'form' : form,
	}, context_instance=RequestContext(request))
Esempio n. 9
0
def _let_user_login(request, user, email, password, next=''):

    user = django_authenticate(email=email, password=password)
    django_login(request, user)
    if next:
        return HttpResponseRedirect(redirect_to=next)
    return HttpResponseRedirect(redirect_to='/')
Esempio n. 10
0
def register(request):
    """
    DataHub account registration form.

    GET returns an HttpResponse containing the account registration form.
    POST creates a name/email/password account and logs the new user in.
    Other links from the page lead to Python Social Auth options (Google,
    Facebook, Twitter, etc).
    """
    # Redirect succesful logins to `next` if set.
    # Failing that `redirect_url`.
    # Failing that, LOGIN_REDIRECT_URL from settings.py.
    redirect_uri = post_or_get(
        request, 'next', fallback=post_or_get(
            request, 'redirect_url', fallback=settings.LOGIN_REDIRECT_URL))
    redirect_absolute_uri = add_query_params_to_url(
        request.build_absolute_uri(redirect_uri),
        {'auth_user': request.user.get_username()})

    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username'].lower()
            email = form.cleaned_data['email'].lower()
            password = form.cleaned_data['password']
            User.objects.create_user(username, email, password)
            # A signal handler in signals.py listens for the pre_save signal
            # and throws an IntegrityError if the user's email address is not
            # unique. Username uniqueness is handled by the model.
            #
            # In the future, another pre_save signal handler will check if a
            # DataHub database exists for the user and create one if it
            # doesn't exist. If the database cannot be created, that handler
            # will throw an exception.
            user = datahub_authenticate(username, password)
            if user is not None and user.is_active:
                django_login(request, user)
                # Append auth_user to redirect_uri so apps like Kibitz can
                # pull the username out of the redirect. This should be
                # removed when Thrift is removed from DataHub.
                redirect_uri = add_query_params_to_url(
                    redirect_uri, {'auth_user': request.user.get_username()})
                return HttpResponseRedirect(redirect_uri)
        else:
            # Form isn't valid. Fall through and return it to the user with
            # errors.
            pass
    else:
        form = RegistrationForm()

    providers = provider_details()
    context = RequestContext(request, {
        'request': request,
        'user': request.user,
        'form': form,
        'providers': providers,
        'next': redirect_uri,
        'absolute_next': redirect_absolute_uri,
        })
    return render_to_response('register.html', context_instance=context)
def globus_callback_authorize(request):
    """
    TODO: This logic 'lets the auth token escape'
    May need to refactor this...
    """
    code = request.GET.get('code')
    try:
        user_token = globus_validate_code(request)
    except Unauthorized as bad_code:
        logger.exception("Globus login failed to validate code: %s" % bad_code)
        app_name = auth_settings.APP_NAME
        site_name = auth_settings.SITE_NAME
        return HttpResponse(
            "In order to use %s you must consent to "
            "releasing your identity details from Globus to %s."
            % (app_name, site_name), status=401)
    if not user_token:
        # Redirect out of the OAuth loop
        return HttpResponseRedirect(auth_settings.LOGOUT_REDIRECT_URL)
    user = authenticate(key=user_token.key)
    django_login(request, user)

    # Apply newly created AuthToken to session
    request.session['username'] = user_token.user.username
    request.session['access_token'] = user_token.key
    # Redirect to 'next'
    next_url = request.session.get('next', '/application')
    return HttpResponseRedirect(next_url)
Esempio n. 12
0
def register(request):
	"""
	Display the registration form, and save the user.
	"""

	# redirect if user is loged in
	if request.user and not request.user.is_anonymous():
		if is_async(request):
			return json_response(request)
		return HttpResponseRedirect(reverse('jobsite_main.views.main'))

	if is_async(request):
		if request.GET.get('submit', False):
			form = UserForm(data=request.GET)
			if form.is_valid():
				user = form.save()
				session_id = request.session.session_key
				auto_authenticate(user)
				django_login(request, user)
				db.update_action_with_user_id(session_id, user)
				return json_response(request)
		else:
			form = UserForm()
			
		return json_response(request, code=INPUT, data=
					render_to_string('blocks/register.html', {'form': form}))
	
	# TODO: register without javascript
	return handle_response(request, { 'content_block': 'blocks/register.html',
			'form': form }, 'base.html')
Esempio n. 13
0
def login_oauth_token(request, backend):
    """
    Authenticate the client using an OAuth access token by using the token to
    retrieve information from a third party and matching that information to an
    existing user.
    """
    warnings.warn("Please use AccessTokenExchangeView instead.", DeprecationWarning)

    backend = request.backend
    if isinstance(backend, social_oauth.BaseOAuth1) or isinstance(backend, social_oauth.BaseOAuth2):
        if "access_token" in request.POST:
            # Tell third party auth pipeline that this is an API call
            request.session[pipeline.AUTH_ENTRY_KEY] = pipeline.AUTH_ENTRY_LOGIN_API
            user = None
            access_token = request.POST["access_token"]
            try:
                user = backend.do_auth(access_token)
            except (HTTPError, AuthException):
                pass
            # do_auth can return a non-User object if it fails
            if user and isinstance(user, User):
                django_login(request, user)
                return JsonResponse(status=204)
            else:
                # Ensure user does not re-enter the pipeline
                request.social_strategy.clean_partial_pipeline(access_token)
                return JsonResponse({"error": "invalid_token"}, status=401)
        else:
            return JsonResponse({"error": "invalid_request"}, status=400)
    raise Http404
Esempio n. 14
0
def login(request):
    """
    Login view
    """
    if request.method == 'POST':
        # Get login data from POST
        password = request.POST.get('password', None)
        username = request.POST.get('access_level', None)

        # Validate credentials
        if username not in ['admin-user', 'readonly-user']:
            # Make sure that people cannot log in as an arbitrary user
            # using faked HTTP requests.
            user = None
        else:
            # If authentication fails, the function returns ``None``.
            user = authenticate(username=username, password=password)

        # Authenticate user
        if user is not None and user.is_active:
                django_login(request, user)
                next_url = request.POST.get('next_url', None)
                if next_url is not None:
                    return redirect(next_url)
                else:
                    return redirect('/')
        else:
            messages.error(request, _('Bad password!'))

    if request.user.is_authenticated():
        return redirect('/')

    context = {'next_url': request.GET.get('next', '')}
    return render(request, 'auth/login.html', context)
Esempio n. 15
0
def login(request):
    """
    Login view
    """
    if request.method == 'POST':
        form = FormAuthenticate(data=request.POST)
        if form.is_valid():
            user = authenticate(
                email=request.POST['email'].lower().replace(" ", ""),
                password=request.POST['password']
            )
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    return HttpResponseRedirect(reverse_lazy('index'))
            else:
                return render_to_response('login.html',
                                          {'form': form, },
                                          context_instance=
                                          RequestContext(request)
                                          )
    else:
        form = FormAuthenticate()
    return render_to_response(
        'login.html', {'form': form, },
        context_instance=RequestContext(request))
Esempio n. 16
0
def login(request):
    '''
    This function handles the logging in of a user, and the submission of the login form from
    the main page.
    '''
    # Set up the response data dict
    responseData = {}

    # First let's check if there is a username and password present in the request
    # Make sure username was included
    if u'username' not in request.POST:
        responseData[u'result'] = u'failed'
        responseData[u'reason'] = u'Username not specified.'
        return HttpResponse(json.dumps(responseData), content_type=u'application/json')

    # Make sure a password was included
    if u'password' not in request.POST:
        responseData[u'result'] = u'failed'
        responseData[u'reason'] = u'Password not specified.'
        return HttpResponse(json.dumps(responseData), content_type=u'application/json')

    # Now let's try to log them in
    u = authenticate(username=request.POST[u'username'], password=request.POST[u'password'])

    # If it is none, login returned a user which means they logged in successfully
    if u is not None:
        # TODO: Check here for is_active?
        django_login(request, u)
        responseData[u'result'] = u'succeeded'
        return HttpResponse(json.dumps(responseData), content_type=u'application/json')
    # If we get here, authentication failed.
    else:
        responseData[u'result'] = u'failed'
        responseData[u'reason'] = u'Invalid username or password.'
        return HttpResponse(json.dumps(responseData), content_type=u'application/json')
Esempio n. 17
0
def old_login(request):
    """
    Log in view
    """
    navbarlinks = list_navbarlinks(request, ["Login", "Help page"])
    navbarlinks.append({"url": "/help#helpsection_loginpage", "title": "Help page", "icon": "question-sign"})
    shortcutlinks = []

    login_failed_msg = False

    if request.method == 'POST':
        login_failed_msg = True
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = authenticate(email=request.POST['username'], password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    request.session["user"] = user.annotator_id.annotator_id
                    login_failed_msg = False
                    return redirect('/interface_main')
    else:
        if request.session.get("user"):
            return redirect('/interface_main', context=RequestContext(request))
        else:
            form = AuthenticationForm()

    return render_to_response('accounts/old_login.html',{'form': form},
                              context_instance=RequestContext(request, {
                                  'login_failed_msg': login_failed_msg,
                                  'navbarlinks': navbarlinks,
                                  'shortcutlinks': shortcutlinks,
                                  "pid_tofeed": request.session.get("pid_tofeed"),
                                  "subject_tofeed": request.session.get("subject_tofeed")
                              }))
Esempio n. 18
0
def login(request):
	if not request.user.is_authenticated():
		if request.method =='POST':
			form = LoginForm(request.POST)
			if form.is_valid():
				username = form.cleaned_data['username']
				password = form.cleaned_data['password']
				user = authenticate(username=username, password=password)
				if user != None:
					if user.is_active:
						django_login(request, user)
						if request.POST.get('next', 'None') == 'None':
							return redirect(reverse('home_index'), context_instance=RequestContext(request))
						else:
							return redirect(request.POST.get('next'), context_instance=RequestContext(request))
					else:
						messages.error(request, 'Your account has been disabled.')
				else:
					messages.error(request, 'Your username and password were incorrect.')
		else:
			form = LoginForm()
	else:
		return redirect(reverse('home_index'), context_instance=RequestContext(request))
	return render_to_response(
		'auth/login.html',
		{'form': form, 'next':request.GET.get('next', 'None')},
		context_instance=RequestContext(request)
	)
Esempio n. 19
0
def signup(request):

    if request.method == 'POST':
        signup_form = UserRegistrationForm(request.POST)

        if signup_form.is_valid():

            user = User.objects.create_user(username=signup_form.cleaned_data['username'],
                                            password=signup_form.cleaned_data[
                                                'password'],
                                            email=signup_form.cleaned_data['email'])

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

            if user is not None:
                if user.is_active:
                    # Login User
                    django_login(request, user)
                    return HttpResponseRedirect('/')
        else:
            return HttpResponseRedirect('/invalid_data/')
    else:
        signup_form = UserRegistrationForm()

    return render_to_response('blogs/signup.html', {
        'signup_form': signup_form
    }, context_instance=RequestContext(request))
Esempio n. 20
0
File: avans.py Progetto: Avans/TWIN
def callback(request):
    token = oauth.Token(request.session['request_token']['oauth_token'], request.session['request_token']['oauth_token_secret'])
    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 Avans.")

    access_token = dict(cgi.parse_qsl(content))
    token = oauth.Token(access_token['oauth_token'], access_token['oauth_token_secret'])
    client = oauth.Client(consumer, token)

    # Check if the user is an employee or not
    resp, content = client.request('https://publicapi.avans.nl/oauth/people/@me', 'GET')
    data = json.loads(content)
    is_student = data['employee'] <> 'true'
    name = data['name']['formatted']
    email = data['emails'][0]

    # Get the username and student number
    resp, content = client.request('https://publicapi.avans.nl/oauth/studentnummer/', 'GET')
    data = json.loads(content)[0]
    username = data['inlognaam'].lower()
    student_number = int(data['studentnummer'])

    user = get_user(username, name, email, is_student, student_number)

    # Log the user in
    user = authenticate(username=username)
    django_login(request, user)

    # Redirect to the main site
    return HttpResponseRedirect('/')
Esempio n. 21
0
def login(request):
    """ Page de connection """

    form = LoginForm()
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('edit_text_static'))
    else:
        c = {}
        c.update(csrf(request))
        state = "Se connecter"

        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    return HttpResponseRedirect(reverse('edit_text_static'))
                else:
                    state = "Your Account is not active,\
                                        please contact the site admin."
            else:
                state = u"Votre nom d'utilisateur et / ou \
                                    votre mot de passe est incorrect. \
                                    Veuillez réessayer."

        c.update({'form': form, 'state': state})
    return render(request, 'login.html', c)
Esempio n. 22
0
def login(request):
    """
    Log in view
    """
    if request.method == 'POST':
        login_form = AuthenticationForm(data=request.POST)
        if login_form.is_valid():
        	email = request.POST['email']
        	try:
        		user = authenticate(email=email, password=request.POST['password'])
        		if user is not None:
        			if user.is_active:
        				django_login(request, user)
        				user = User.objects.get(email=email)
        				
        				try:
        					student=user.student_set.get()
        					return HttpResponseRedirect("/student")
        				except:
        					try:
        						mentor = user.mentor_set.get()
        						return HttpResponseRedirect("/mentor")
        					except:
        						raise Http404("User does not exist.")
        		else:
        			return HttpResponseRedirect('/invalid_login')
        	except:
        		raise HttpResponseRedirect('/invalid_login')
            
    else:
        login_form = AuthenticationForm()
    return render_to_response('projects_app/login.html', {
        'form': login_form,
    }, context_instance=RequestContext(request))
Esempio n. 23
0
def login(request):
    if request.method in ['GET', 'HEAD']:
        if request.user.is_authenticated():
            try:
                player = Player.objects.get(user=request.user)
                return redirect(reverse('player', kwargs={'username': player.user.username}))
            except Exception:
                return HttpResponseServerError("<h1>Your user is not associated with a player!</h1>")
        else:
            return render(request, 'murpi_core/login.html')
    elif request.method == 'POST':
        if dict_has_keys(request.POST, ('username', 'password'), check_not_empty=True):
            user = authenticate(username=request.POST['username'], password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    if user.player:
                        django_login(request, user)
                        return redirect(reverse("player", kwargs={"username": user.username}))
                    else:
                        error(request, 'Your user account is broken! Please contact an admin.')
                        return redirect(reverse("login"))
                else:
                    error(request, 'Your account is disabled!')
                    return redirect(reverse("login"))
            else:
                request.session['username'] = request.POST['username']
                error(request, 'Incorrect username or password.')
                return redirect(reverse("login"))
        else:
            request.session['username'] = request.POST['username']
            error(request, 'Username or password cannot be empty')
            return redirect(reverse("login"))
    else:
        raise Http404('Only GET, POST, and HEAD HTTP methods allowed.')
Esempio n. 24
0
def activation(request, code=None):
    if not code:
        code = request.GET.get('code', None)

    if request.user.is_authenticated() or request.method == 'POST':
        return redirect('profile_view')

    if code:
        claim = get_object_or_None(Claim, activation_code=code)

        if not claim:
            return {'fail': _('Activation code invalid.')}

        elif claim.user.is_active:
            return {'fail': _('Claim has been already activated.')}

        elif claim.activate():
            send_email(settings.NOTIFY_EMAIL, 'notice', {'claim': claim, 'action': 'activation'})
            claim.user.backend = 'django.contrib.auth.backends.ModelBackend'
            django_login(request, claim.user)

        else:
            return {'fail': _('Activation failed.') }

    return {}
Esempio n. 25
0
def login(request):
    """ Try to log in a user """
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        site = request.POST.get('next', '/manage')

        user = django_auth(username=username, password=password)

        if user is not None:
            if user.is_active:
                django_login(request, user)
                return redirect(site)

    form = AuthenticationForm(request)

    form.fields['username'].widget.attrs.update({
            'placeholder': 'username'
        })
    form.fields['password'].widget.attrs.update({
            'placeholder': 'password'
        })

    site = request.GET.get('next', '/manage')

    return render(request, 'blog/login.html', {
        'form': form,
        'next': site,
        'request': request,
    })
Esempio n. 26
0
def register(request):

    if request.method == 'GET':
        ''' Show the registration page '''
        return render(request, "keyvalue/register.html")

    else:
        if 'username' in request.POST and 'email' in request.POST and \
                'password1' in request.POST and 'password2' in request.POST:
            username = request.POST['username']
            email = request.POST['email']
            password1 = request.POST['password1']
            password2 = request.POST['password2']
        else:
            return render(request, "keyvalue/register.html", {'error': "Please fill in all fields"})

        if password1 != password2:
            return render(request, "keyvalue/register.html", {'error': "The passwords do not match"})

        try:
            # Create the new account
            user = User.objects.create_user(username=username, email=email, password=password1)
            setup_new_user(user)

            # Log the new account in
            user = authenticate(username=username,password=password1)
            django_login(request, user)

            return render(request, "keyvalue/register.html", {'success': "Registration successful!"})

        except IntegrityError:
            return render(request, "keyvalue/register.html", {'error': "This username was already taken or invalid"})
        except Exception:
            return render(request, "keyvalue/register.html", {'error': "An error occurred: invalid data?"})
Esempio n. 27
0
def internal_login(request):
    """ Internal login using Django authentication framework """
    custom_log(request, "Internal login requested. back_url=%s" % request.GET.get("next"), level="debug")
    params = request.GET.dict()
    params["_sso"] = "internal"
    ret = {}
    browser = request.browser
    if browser is None:
        custom_log(request, "Browser is not set. Redirect to first step authentication")
        return redirect_with_get_params("login_frontend.authentication_views.firststepauth", params)

    if request.GET.get("next") is None:
        # No back url is defined. Go to front page.
        custom_log(request, "No back URL is defined. Redirect to the front page", level="debug")
        return HttpResponseRedirect(reverse("login_frontend.views.indexview"))



    # TODO: static auth level
    if browser.get_auth_level() >= Browser.L_STRONG:
        back_url = request.GET.get("next")
        custom_log(request, "User is authenticated with strong authentication. Redirecting back to %s" % back_url, level="info")
        (user, _) = DjangoUser.objects.get_or_create(username=browser.user.username, defaults={"email": browser.user.email, "is_staff": False, "is_active": True, "is_superuser": False, "last_login": datetime.datetime.now(), "date_joined": datetime.datetime.now()})
        user.backend = 'django.contrib.auth.backends.ModelBackend' # Horrible hack.
        django_login(request, user)

        return HttpResponseRedirect(back_url)

    custom_log(request, "More authentication is required. Redirect to first step authentication", level="debug")
    return redirect_with_get_params("login_frontend.authentication_views.firststepauth", params)
Esempio n. 28
0
def login(request):
    try:
        user = authenticate(shibd_meta=request.META)
        if not user:
            raise ShibbolethException(
                _("Failed to login the user. "
                  "Shibboleth META headers missing. "
                  "Check the Apache mod_shibd is active and /shibboleth is protected.")
            )
        if not user.is_active:
            logger.warn("Shibboleth login attempt for inactive user: {}".format(user.username))
            raise ShibbolethException(
                _("The user account has been disabled.")
            )

        django_login(request, user)
        logger.debug("Shibboleth login: {}".format(user.username))
        
        redirect_to = request.GET.get(REDIRECT_FIELD_NAME, '')
        if not is_safe_url(url=redirect_to, host=request.get_host()):
            redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
        
        return HttpResponseRedirect(redirect_to)
    
    except ShibbolethException as e:
        return HttpResponse(e.message, content_type='text/plain', status=403)
Esempio n. 29
0
def login(request, user):
    partner_pk = request.session[settings.PARTNER_SESSION_KEY] \
            if settings.PARTNER_SESSION_KEY in request.session \
            else None
    django_login(request, user)
    if partner_pk:
        request.session[settings.PARTNER_SESSION_KEY] = partner_pk
Esempio n. 30
0
def register(request):
    if (request.POST.get('password', '') == request.POST.get('password_confirmation', '')):
        email = request.POST.get('email', '')
        fname = request.POST.get('first', '')
        lname = request.POST.get('last', '')
        password = request.POST.get('password', '')
        
        
        # The user model is a preset django model
        try:
            user = User.objects.create_user(username=email, password=password, email=email, first_name=fname, last_name=lname)
            user.save()
            user = authenticate(username=email, password=password)
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    # return HttpResponse("You are now logged in")
                    request.session['mid'] = user.id
                    return HttpResponseRedirect ('/tasks/')
            
        except:
            return HttpResponse("Sorry please try again with different inputs")
        
    else:
        # print request.POST.get('password', '')
        # print request.POST.get('password_confirmation', '')
        return HttpResponse("your password and confirmation did not match")
Esempio n. 31
0
def sms_login(request, *args, **kwargs):

    # Check session variables to find information carried forward.
    access_field = settings.USERNAME_FIELD
    # This is the key field name. Probably username or email

    if access_field in request.session:
        if request.session[access_field] != "":
            access_key = request.session[access_field]
        else:
            access_key = ""
    else:
        access_key = ""
    if settings.DEBUG:
        # print(request.GET)
        print("SMS_LOGIN.GET:", access_field, ":[%s]" % (access_key))
        # print(request.POST)
        print(args)

    next = ""

    # Passing next parameter through to form
    if request.GET:
        if 'next' in request.GET:
            next = request.GET['next']

    if settings.DEBUG:
        print("We got a next value of:", next)
    if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        if request.POST['login'].lower() == 'resend code':
            if settings.DEBUG:
                print("Resending Code for %s" % request.POST[access_field])
            # form = SMSCodeForm(request.POST)
            # form.username = request.POST['username']
            request.session[access_field] = request.POST[access_field]
            return HttpResponseRedirect(reverse('accounts:sms_code'))
        if form.is_valid():
            print("Authenticating...")
            access_key = form.cleaned_data[access_field].lower()
            password = form.cleaned_data['password'].lower()
            sms_code = form.cleaned_data['sms_code']

            if not validate_sms(access_key=access_key, smscode=sms_code):
                messages.error(request, "Invalid Access Code.")
                return render_to_response('accounts/login.html',
                                          {'form': AuthenticationForm(),
                                           'next': next},
                                          RequestContext(request))
            # DONE: Trying to handle LDAP Errors. eg. Not available
            try:
                user = authenticate(username=access_key, password=password)
            except (ldap3.LDAPBindError,
                    ldap3.LDAPSASLPrepError,
                    ldap3.LDAPSocketOpenError):
                print("We got an LDAP Error - Bind:",dir(ldap3.LDAPBindError),
                    "\nSASL Prep:", ldap3.LDAPSASLPrepError,
                    "\nSocketOpenError:",ldap3.LDAPSocketOpenError)
                messages.error(request, "We had a problem reaching the Directory Server")
                return render_to_response('accounts/login.html', {'next': next},
                                      RequestContext(request))

            #######

            if user is not None:

                if user.is_active:
                    django_login(request, user)

                    # DONE: Set a session variable to identify as
                    # master account and not a subacc
                    session_device(request,
                                    "True",
                                    Session="auth_master")

                    # DONE: Now Send a message on login
                    if user.notify_activity in "ET":
                        send_activity_message(request,
                                              user)
                    # Otherwise don't send a message
                    if next != "":
                        return HttpResponseRedirect(next)
                    else:
                        return HttpResponseRedirect(reverse('home'))
                else:

                    messages.error(request, "Your account is not active.")
                    args = {'next': next}
                    return HttpResponseRedirect(reverse('sms_code', args))
            else:
                messages.error(request, "Invalid username or password.")
                return render_to_response('accounts/login.html',
                                          {'form': AuthenticationForm(),
                                           'next': next},
                                          RequestContext(request))
        else:
            print("Error with the POST form", )
            return render_to_response('accounts/login.html',
                                      {'form': form,
                                       'next': next},
                                      RequestContext(request))
    else:
        if access_field in request.session:
            access_key = request.session[access_field]
        else:
            access_key = ""
        if settings.DEBUG:
            print("in sms_login. Setting up Form [", access_key, "]")

        form = AuthenticationForm(initial={access_field: access_key})
    if settings.DEBUG:
        # print(form)
        print("Dropping to render_to_response in sms_login")

    return render_to_response('accounts/login.html', {'form': form,
                                                      'next': next},
                              RequestContext(request))
Esempio n. 32
0
 def process_login(self):
     django_login(self.request, self.user)
Esempio n. 33
0
def login_get_access(request):
    print('*********** login_get_access ************')
    if 'state' not in request.session:
        request.session['state'] = 'blah123'  # 'state'
    if request.GET['state'] != request.session['state']:
        print("login_get_access> get state: <%s> and session <%s>" %
              (request.GET['state'], request.session['state']))
        #return HttpResponseRedirect('/')
        return render(request, 'msg.html',
                      {'msg': 'session is expired. Try to login again.'})
    data = {
        'client_id': client_id_login,
        'client_secret': client_secret_login,
        'code': request.GET['code'],
        'redirect_uri': host  # host+'/add_hook'
    }
    res = requests.post('https://github.com/login/oauth/access_token',
                        data=data)
    print("response: ")
    print(res.text)
    atts = res.text.split('&')
    d = {}
    try:
        for att in atts:
            keyv = att.split('=')
            d[keyv[0]] = keyv[1]
        access_token = d['access_token']
        request.session['access_token'] = access_token
        print('access_token: ' + access_token)
    except Exception as e:
        print("exception: " + str(e))
        print("no access token")
        print("response: %s" % res.text)
        return render(
            request, 'msg.html',
            {'msg': 'Missing token from Github API. Try to login again'})

    g = Github(access_token)
    email = g.get_user().email
    username = g.get_user().login
    if email == '' or type(email) == type(None):
        return render(
            request, 'msg.html',
            {'msg': 'You have to make you email public and try again'})
    request.session['avatar_url'] = g.get_user().avatar_url
    print('avatar_url: ' + request.session['avatar_url'])
    try:
        print("looking for email: <%s>" % (str(email)))
        user = OUser.objects.get(email=email)
        user.username = username
        user.save()
    except Exception as e:
        try:
            print("number of users: %d" % (len(OUser.objects.all())))
            print("Exception: %s" % (str(e)))
            print("looking for username: <%s>" % (str(username)))
            user = OUser.objects.get(username=username)
            user.email = email
            user.save()
        except:
            print("Exception: %s" % (str(e)))
            print('<%s,%s>' % (email, username))
            # The password is never important but we set it here because it is required by User class
            print("Now will create the user: "******"username: "******"password: "******"email: " + email)
            user = OUser.objects.create_user(username=username,
                                             password=request.session['state'],
                                             email=email)
            user.save()
    django_login(request, user)
    print('The used access_token: ' + access_token)
    sys.stdout.flush()
    sys.stderr.flush()
    return HttpResponseRedirect('/')
Esempio n. 34
0
def registration(request):
    '''
    A form to allow for registration of new users
    '''
    template_data = {}
    template_data.update(csrf(request))

    # Don't use captcha when registering through an app
    is_app = check_request_amazon(request) or check_request_android(request)
    FormClass = RegistrationFormNoCaptcha if is_app else RegistrationForm

    # Don't show captcha if the global parameter is false
    if not settings.WGER_SETTINGS['USE_RECAPTCHA']:
        FormClass = RegistrationFormNoCaptcha

    # Redirect regular users, in case they reached the registration page
    if request.user.is_authenticated(
    ) and not request.user.userprofile.is_temporary:
        return HttpResponseRedirect(reverse('core:dashboard'))

    if request.method == 'POST':
        form = FormClass(data=request.POST)

        # If the data is valid, log in and redirect
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            email = form.cleaned_data['email']
            user = Django_User.objects.create_user(username, email, password)
            user.save()

            # Pre-set some values of the user's profile
            language = Language.objects.get(
                short_name=translation.get_language())
            user.userprofile.notification_language = language

            # Set default gym, if needed
            gym_config = GymConfig.objects.get(pk=1)
            if gym_config.default_gym:
                user.userprofile.gym = gym_config.default_gym

                # Create gym user configuration object
                config = GymUserConfig()
                config.gym = gym_config.default_gym
                config.user = user
                config.save()

            user.userprofile.save()

            user = authenticate(username=username, password=password)
            django_login(request, user)
            messages.success(request, _('You were successfully registered'))
            return HttpResponseRedirect(reverse('core:dashboard'))
    else:
        form = FormClass()

    template_data['form'] = form
    template_data['title'] = _('Register')
    template_data['form_fields'] = [i for i in form]
    template_data['form_action'] = reverse('core:user:registration')
    template_data['submit_text'] = _('Register')
    template_data['extend_template'] = 'base.html'

    return render(request, 'form.html', template_data)
Esempio n. 35
0
def auth_receive(request):
    if 's' in request.GET and request.GET['s'] == "logout":
        # This was a logout request
        return HttpResponseRedirect('/')

    if 'i' not in request.GET:
        return HttpResponse("Missing IV in url!", status=400)
    if 'd' not in request.GET:
        return HttpResponse("Missing data in url!", status=400)

    # Set up an AES object and decrypt the data we received
    decryptor = AES.new(base64.b64decode(settings.PGAUTH_KEY), AES.MODE_CBC,
                        base64.b64decode(str(request.GET['i']), "-_"))
    s = decryptor.decrypt(base64.b64decode(str(request.GET['d']),
                                           "-_")).rstrip(b' ').decode('utf8')

    # Now un-urlencode it
    try:
        data = parse_qs(s, strict_parsing=True)
    except ValueError:
        return HttpResponse("Invalid encrypted data received.", status=400)

    # Check the timestamp in the authentication
    if (int(data['t'][0]) < time.time() - 10):
        return HttpResponse("Authentication token too old.", status=400)

    # Update the user record (if any)
    try:
        user = User.objects.get(username=data['u'][0])
        # User found, let's see if any important fields have changed
        changed = []
        if user.first_name != data['f'][0]:
            user.first_name = data['f'][0]
            changed.append('first_name')
        if user.last_name != data['l'][0]:
            user.last_name = data['l'][0]
            changed.append('last_name')
        if user.email != data['e'][0]:
            user.email = data['e'][0]
            changed.append('email')
        if changed:
            user.save(update_fields=changed)
    except User.DoesNotExist:
        # User not found, create it!

        # NOTE! We have some legacy users where there is a user in
        # the database with a different userid. Instead of trying to
        # somehow fix that live, give a proper error message and
        # have somebody look at it manually.
        if User.objects.filter(email=data['e'][0]).exists():
            return HttpResponse(
                """A user with email %s already exists, but with
a different username than %s.

This is almost certainly caused by some legacy data in our database.
Please send an email to [email protected], indicating the username
and email address from above, and we'll manually merge the two accounts
for you.

We apologize for the inconvenience.
""" % (data['e'][0], data['u'][0]),
                content_type='text/plain')

        if getattr(settings, 'PGAUTH_CREATEUSER_CALLBACK', None):
            res = getattr(settings, 'PGAUTH_CREATEUSER_CALLBACK')(
                data['u'][0],
                data['e'][0],
                ['f'][0],
                data['l'][0],
            )
            # If anything is returned, we'll return that as our result.
            # If None is returned, it means go ahead and create the user.
            if res:
                return res

        user = User(
            username=data['u'][0],
            first_name=data['f'][0],
            last_name=data['l'][0],
            email=data['e'][0],
            password='******',
        )
        user.save()

    # Ok, we have a proper user record. Now tell django that
    # we're authenticated so it persists it in the session. Before
    # we do that, we have to annotate it with the backend information.
    user.backend = "%s.%s" % (AuthBackend.__module__, AuthBackend.__name__)
    django_login(request, user)

    # Signal that we have information about this user
    auth_user_data_received.send(
        sender=auth_receive,
        user=user,
        userdata={
            'secondaryemails':
            data['se'][0].split(',') if 'se' in data else []
        })

    # Finally, check of we have a data package that tells us where to
    # redirect the user.
    if 'd' in data:
        (ivs, datas) = data['d'][0].split('$')
        decryptor = AES.new(
            SHA.new(settings.SECRET_KEY.encode('ascii')).digest()[:16],
            AES.MODE_CBC, base64.b64decode(ivs, b"-_"))
        s = decryptor.decrypt(base64.b64decode(
            datas, "-_")).rstrip(b' ').decode('utf8')
        try:
            rdata = parse_qs(s, strict_parsing=True)
        except ValueError:
            return HttpResponse("Invalid encrypted data received.", status=400)
        if 'r' in rdata:
            # Redirect address
            return HttpResponseRedirect(rdata['r'][0])
    # No redirect specified, see if we have it in our settings
    if hasattr(settings, 'PGAUTH_REDIRECT_SUCCESS'):
        return HttpResponseRedirect(settings.PGAUTH_REDIRECT_SUCCESS)
    return HttpResponse(
        "Authentication successful, but don't know where to redirect!",
        status=500)
Esempio n. 36
0
@anonymous_only
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            # Register
            form.save()
            # Authenticate
            user = authenticate(
                username=form.cleaned_data['email'],
                password=form.cleaned_data['password'],
            )
            if not user:
                return HttpResponseRedirect(reverse('auth:login'))
            # Login
            django_login(request, user)
            return HttpResponseRedirect('/')
    else:
        form = RegisterForm()
    return render(request, 'auth/register.html', {
        'form': form,
    })


@anonymous_only
def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            user = form.get_user()
            django_login(request, user)
Esempio n. 37
0
def create_account_with_params(request, params):
    """
    Given a request and a dict of parameters (which may or may not have come
    from the request), create an account for the requesting user, including
    creating a comments service user object and sending an activation email.
    This also takes external/third-party auth into account, updates that as
    necessary, and authenticates the user for the request's session.

    Does not return anything.

    Raises AccountValidationError if an account with the username or email
    specified by params already exists, or ValidationError if any of the given
    parameters is invalid for any other reason.

    Issues with this code:
    * It is non-transactional except where explicitly wrapped in atomic to
      alleviate deadlocks and improve performance. This means failures at
      different places in registration can leave users in inconsistent
      states.
    * Third-party auth passwords are not verified. There is a comment that
      they are unused, but it would be helpful to have a sanity check that
      they are sane.
    * The user-facing text is rather unfriendly (e.g. "Username must be a
      minimum of two characters long" rather than "Please use a username of
      at least two characters").
    * Duplicate email raises a ValidationError (rather than the expected
      AccountValidationError). Duplicate username returns an inconsistent
      user message (i.e. "An account with the Public Username '{username}'
      already exists." rather than "It looks like {username} belongs to an
      existing account. Try again with a different username.") The two checks
      occur at different places in the code; as a result, registering with
      both a duplicate username and email raises only a ValidationError for
      email only.
    """
    # Copy params so we can modify it; we can't just do dict(params) because if
    # params is request.POST, that results in a dict containing lists of values
    params = dict(params.items())

    # allow to define custom set of required/optional/hidden fields via configuration
    extra_fields = configuration_helpers.get_value(
        'REGISTRATION_EXTRA_FIELDS',
        getattr(settings, 'REGISTRATION_EXTRA_FIELDS', {})
    )
    # registration via third party (Google, Facebook) using mobile application
    # doesn't use social auth pipeline (no redirect uri(s) etc involved).
    # In this case all related info (required for account linking)
    # is sent in params.
    # `third_party_auth_credentials_in_api` essentially means 'request
    # is made from mobile application'
    third_party_auth_credentials_in_api = 'provider' in params
    is_third_party_auth_enabled = third_party_auth.is_enabled()

    if is_third_party_auth_enabled and (pipeline.running(request) or third_party_auth_credentials_in_api):
        params["password"] = generate_password()

    # in case user is registering via third party (Google, Facebook) and pipeline has expired, show appropriate
    # error message
    if is_third_party_auth_enabled and ('social_auth_provider' in params and not pipeline.running(request)):
        raise ValidationError(
            {'session_expired': [
                _(u"Registration using {provider} has timed out.").format(
                    provider=params.get('social_auth_provider'))
            ]}
        )

    extended_profile_fields = configuration_helpers.get_value('extended_profile_fields', [])
    # Can't have terms of service for certain SHIB users, like at Stanford
    registration_fields = getattr(settings, 'REGISTRATION_EXTRA_FIELDS', {})
    tos_required = (
        registration_fields.get('terms_of_service') != 'hidden' or
        registration_fields.get('honor_code') != 'hidden'
    )

    form = AccountCreationForm(
        data=params,
        extra_fields=extra_fields,
        extended_profile_fields=extended_profile_fields,
        do_third_party_auth=False,
        tos_required=tos_required,
    )
    custom_form = get_registration_extension_form(data=params)

    # Perform operations within a transaction that are critical to account creation
    with outer_atomic(read_committed=True):
        # first, create the account
        (user, profile, registration) = do_create_account(form, custom_form)

        third_party_provider, running_pipeline = _link_user_to_third_party_provider(
            is_third_party_auth_enabled, third_party_auth_credentials_in_api, user, request, params,
        )

        new_user = authenticate_new_user(request, user.username, params['password'])
        django_login(request, new_user)
        request.session.set_expiry(0)

    # Check if system is configured to skip activation email for the current user.
    skip_email = _skip_activation_email(
        user, running_pipeline, third_party_provider,
    )

    if skip_email:
        registration.activate()
    else:
        compose_and_send_activation_email(user, profile, registration)

    # Perform operations that are non-critical parts of account creation
    create_or_set_user_attribute_created_on_site(user, request.site)

    preferences_api.set_user_preference(user, LANGUAGE_KEY, get_language())

    if settings.FEATURES.get('ENABLE_DISCUSSION_EMAIL_DIGEST'):
        try:
            enable_notifications(user)
        except Exception:  # pylint: disable=broad-except
            log.exception(u"Enable discussion notifications failed for user {id}.".format(id=user.id))

    _track_user_registration(user, profile, params, third_party_provider)

    # Announce registration
    REGISTER_USER.send(sender=None, user=user, registration=registration)

    create_comments_service_user(user)

    try:
        _record_registration_attributions(request, new_user)
    # Don't prevent a user from registering due to attribution errors.
    except Exception:   # pylint: disable=broad-except
        log.exception('Error while attributing cookies to user registration.')

    # TODO: there is no error checking here to see that the user actually logged in successfully,
    # and is not yet an active user.
    if new_user is not None:
        AUDIT_LOG.info(u"Login success on new account creation - {0}".format(new_user.username))

    return new_user
Esempio n. 38
0
def facebook_login(request):
    code = request.GET.get('code')
    app_access_token = '{}|{}'.format(
        settings.FACEBOOK_APP_ID,
        settings.FACEBOOK_SECRET_CODE,
    )

    class GetAccessTokenException(Exception):
        def __init__(self, *args, **kwargs):
            error_dict = args[0]['data']['error']
            self.code = error_dict['code']
            self.message = error_dict['message']
            self.is_valid = error_dict['is_valid']
            self.scopes = error_dict['scopes']

    class DebugTokenException(Exception):
        def __init__(self, *args, **kwargs):
            error_dict = args[0]['data']['error']
            self.code = error_dict['code']
            self.message = error_dict['message']

    def add_message_and_redirect_referer():
        error_message_for_user = '******'
        messages.error(request, error_message_for_user)
        return redirect(request.META['HTTP_REFERER'])

    def get_access_token(code):
        url_access_token = 'https://graph.facebook.com/v2.9/oauth/access_token'
        redirect_uri = '{}://{}{}'.format(
            request.scheme,
            request.META['HTTP_HOST'],
            request.path,
        )
        url_access_token_params = {
            'client_id': settings.FACEBOOK_APP_ID,
            'redirect_uri': redirect_uri,
            'client_secret': settings.FACEBOOK_SECRET_CODE,
            'code': code,
        }
        response = requests.get(url_access_token,
                                params=url_access_token_params)
        result = response.json()
        if 'access_token' in result:
            return result['access_token']
        elif 'error' in result:
            raise GetAccessTokenException(result)
        else:
            raise Exception('Unknown error')

    def debug_token(token):
        url_debug_token = 'https://graph.facebook.com/debug_token'
        url_debug_token_params = {
            'input_token': token,
            'access_token': app_access_token
        }
        response = requests.get(url_debug_token, url_debug_token_params)
        result = response.json()
        if 'error' in result['data']:
            raise DebugTokenException(result)
        else:
            return result

    def get_user_info(user_id, token):
        url_user_info = 'https://graph.facebook.com/v2.9/{user_id}'.format(
            user_id=user_id)
        url_user_info_params = {
            'access_token':
            token,
            'fields':
            ','.join([
                'id',
                'name',
                'email',
                'first_name',
                'last_name',
                'picture.type(large)',
                'gender',
            ])
        }
        response = requests.get(url_user_info, params=url_user_info_params)
        result = response.json()
        return result

    if not code:
        return add_message_and_redirect_referer()
    try:
        access_token = get_access_token(code)
        debug_result = debug_token(access_token)
        user_info = get_user_info(user_id=debug_result['data']['user_id'],
                                  token=access_token)
        user = User.objects.get_or_create_facebook_user(user_info)
        django_login(request, user)
        return redirect(request.META['HTTP_REFERER'])

    except GetAccessTokenException as e:
        print(e.code)
        print(e.message)
        return add_message_and_redirect_referer()
    except DebugTokenException as e:
        print(e.code)
        print(e.message)
        return add_message_and_redirect_referer()
Esempio n. 39
0
def register(request):
    """
    DataHub account registration form.

    GET returns an HttpResponse containing the account registration form.
    POST creates a name/email/password account and logs the new user in.
    Other links from the page lead to Python Social Auth options (Google,
    Facebook, Twitter, etc).
    """
    # Redirect succesful logins to `next` if set.
    # Failing that `redirect_url`.
    # Failing that, LOGIN_REDIRECT_URL from settings.py.
    redirect_uri = post_or_get(request,
                               'next',
                               fallback=post_or_get(
                                   request,
                                   'redirect_url',
                                   fallback=settings.LOGIN_REDIRECT_URL))
    redirect_absolute_uri = add_query_params_to_url(
        request.build_absolute_uri(redirect_uri),
        {'auth_user': request.user.get_username()})

    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username'].lower()
            email = form.cleaned_data['email'].lower()
            password = form.cleaned_data['password']
            User.objects.create_user(username, email, password)
            # A signal handler in signals.py listens for the pre_save signal
            # and throws an IntegrityError if the user's email address is not
            # unique. Username uniqueness is handled by the model.
            #
            # In the future, another pre_save signal handler will check if a
            # DataHub database exists for the user and create one if it
            # doesn't exist. If the database cannot be created, that handler
            # will throw an exception.
            user = datahub_authenticate(username, password)

            if user is not None and user.is_active:
                django_login(request, user)
                # Append auth_user to redirect_uri so apps like Kibitz can
                # pull the username out of the redirect. This should be
                # removed when Thrift is removed from DataHub.
                redirect_uri = add_query_params_to_url(
                    redirect_uri, {'auth_user': request.user.get_username()})
                return HttpResponseRedirect(redirect_uri)
        else:
            # Form isn't valid. Fall through and return it to the user with
            # errors.
            pass
    else:
        form = RegistrationForm()

    providers = provider_details()
    context = RequestContext(
        request, {
            'request': request,
            'user': request.user,
            'form': form,
            'providers': providers,
            'next': redirect_uri,
            'absolute_next': redirect_absolute_uri
        })
    return render_to_response('register.html', context_instance=context)
Esempio n. 40
0
def auto_auth(request):
    """
    Create or configure a user account, then log in as that user.

    Enabled only when
    settings.FEATURES['AUTOMATIC_AUTH_FOR_TESTING'] is true.

    Accepts the following querystring parameters:
    * `username`, `email`, and `password` for the user account
    * `full_name` for the user profile (the user's full name; defaults to the username)
    * `staff`: Set to "true" to make the user global staff.
    * `course_id`: Enroll the student in the course with `course_id`
    * `roles`: Comma-separated list of roles to grant the student in the course with `course_id`
    * `no_login`: Define this to create the user but not login
    * `redirect`: Set to "true" will redirect to the `redirect_to` value if set, or
        course home page if course_id is defined, otherwise it will redirect to dashboard
    * `redirect_to`: will redirect to to this url
    * `is_active` : make/update account with status provided as 'is_active'
    If username, email, or password are not provided, use
    randomly generated credentials.
    """

    # Generate a unique name to use if none provided
    generated_username = uuid.uuid4().hex[0:30]
    generated_password = generate_password()

    # Use the params from the request, otherwise use these defaults
    username = request.GET.get('username', generated_username)
    password = request.GET.get('password', generated_password)
    email = request.GET.get('email', username + "@example.com")
    full_name = request.GET.get('full_name', username)
    is_staff = str2bool(request.GET.get('staff', False))
    is_superuser = str2bool(request.GET.get('superuser', False))
    course_id = request.GET.get('course_id')
    redirect_to = request.GET.get('redirect_to')
    is_active = str2bool(request.GET.get('is_active', True))

    # Valid modes: audit, credit, honor, no-id-professional, professional, verified
    enrollment_mode = request.GET.get('enrollment_mode', 'honor')

    # Parse roles, stripping whitespace, and filtering out empty strings
    roles = _clean_roles(request.GET.get('roles', '').split(','))
    course_access_roles = _clean_roles(
        request.GET.get('course_access_roles', '').split(','))

    redirect_when_done = str2bool(request.GET.get('redirect',
                                                  '')) or redirect_to
    login_when_done = 'no_login' not in request.GET

    restricted = settings.FEATURES.get('RESTRICT_AUTOMATIC_AUTH', True)
    if is_superuser and restricted:
        return HttpResponseForbidden(_('Superuser creation not allowed'))

    form = AccountCreationForm(data={
        'username': username,
        'email': email,
        'password': password,
        'name': full_name,
    },
                               tos_required=False)

    # Attempt to create the account.
    # If successful, this will return a tuple containing
    # the new user object.
    try:
        user, profile, reg = do_create_account(form)
    except (AccountValidationError, ValidationError):
        if restricted:
            return HttpResponseForbidden(
                _('Account modification not allowed.'))
        # Attempt to retrieve the existing user.
        user = User.objects.get(username=username)
        user.email = email
        user.set_password(password)
        user.is_active = is_active
        user.save()
        profile = UserProfile.objects.get(user=user)
        reg = Registration.objects.get(user=user)
    except PermissionDenied:
        return HttpResponseForbidden(_('Account creation not allowed.'))

    user.is_staff = is_staff
    user.is_superuser = is_superuser
    user.save()

    if is_active:
        reg.activate()
        reg.save()

    # ensure parental consent threshold is met
    year = datetime.date.today().year
    age_limit = settings.PARENTAL_CONSENT_AGE_LIMIT
    profile.year_of_birth = (year - age_limit) - 1
    profile.save()

    create_or_set_user_attribute_created_on_site(user, request.site)

    # Enroll the user in a course
    course_key = None
    if course_id:
        course_key = CourseLocator.from_string(course_id)
        CourseEnrollment.enroll(user, course_key, mode=enrollment_mode)

        # Apply the roles
        for role in roles:
            assign_role(course_key, user, role)

        for role in course_access_roles:
            CourseAccessRole.objects.update_or_create(user=user,
                                                      course_id=course_key,
                                                      org=course_key.org,
                                                      role=role)

    # Log in as the user
    if login_when_done:
        user = authenticate_new_user(request, username, password)
        django_login(request, user)

    create_comments_service_user(user)

    if redirect_when_done:
        if redirect_to:
            # Redirect to page specified by the client
            redirect_url = redirect_to
        elif course_id:
            # Redirect to the course homepage (in LMS) or outline page (in Studio)
            try:
                redirect_url = reverse(course_home_url_name(course_key),
                                       kwargs={'course_id': course_id})
            except NoReverseMatch:
                redirect_url = reverse('course_handler',
                                       kwargs={'course_key_string': course_id})
        else:
            # Redirect to the learner dashboard (in LMS) or homepage (in Studio)
            try:
                redirect_url = reverse('dashboard')
            except NoReverseMatch:
                redirect_url = reverse('home')

        return redirect(redirect_url)
    else:
        response = JsonResponse({
            'created_status':
            'Logged in' if login_when_done else 'Created',
            'username':
            username,
            'email':
            email,
            'password':
            password,
            'user_id':
            user.id,  # pylint: disable=no-member
            'anonymous_id':
            anonymous_id_for_user(user, None),
        })
    response.set_cookie('csrftoken', csrf(request)['csrf_token'])
    return response
Esempio n. 41
0
    def post(self, request, **kwargs):
        #from user_authn.views.login import _check_excessive_login_attempts
        from student.models import LoginFailures
        #from openedx.core.djangoapps.user_authn.views.login import _check_excessive_login_attempts
        self.data = request.POST.dict()
        if not ('uservalue' and 'sendotptype' and 'password' in self.data):
            return JsonResponse({
                "status": 400,
                "message": "Please enter Valid Mobile Number or Email Address or password",
            })
        if self.data.get('sendotptype') == "mobile":
            mobile = self.data.get('uservalue')
            user = User.objects.get(extrafields__phone=mobile)
            email = user.email
        else:
            email = self.data.get('uservalue')

        password = self.data.get('password')
        if not password:
            return JsonResponse({
                "status": 400,
                "message": "Password fiels can not be blank",
            })
        try:
            user = User.objects.get(email=email)
            if not user.is_active:
                registration = Registration.objects.get(user=user)
                profile = UserProfile.objects.get(user=user)
                compose_and_send_activation_email(user, profile, registration)
                return JsonResponse({
                    "status": 400,
                    "message": "Please check mail and active it.",
               })
            try:
                if user and LoginFailures.is_feature_enabled():
                    if LoginFailures.is_user_locked_out(user):
                        raise AuthFailedError(_('This account has been temporarily locked due '
                                    'to excessive login failures. Try again later.'))
                #_check_excessive_login_attempts(user)
            except Exception as e:
                logs.info(e.message)
                return JsonResponse(status=200, data={
                    "status": 400,
                    "message": "Login attempt failed",
            })

            new_user = authenticate_new_user(request, user.username, password)
            #compose_and_send_activation_email(user, profile)
            #compose_and_send_activation_email(user, profile, registration)
            django_login(request, new_user)
            request.session.set_expiry(604800 * 4)
            if not new_user.extrafields.rpincode:
                response =  JsonResponse(status=200, data={
                    "status":200,
                    "message": "profile",
                    "userid":new_user.id,
                    "number":new_user.extrafields.rcountry_code
                 })
            else:
                response = JsonResponse(status=200, data={
                    "status": 200,
                    "message": "success",
            })
            devlog = set_logged_in_cookies(request, response, new_user)
            return devlog

        except Exception as e:
            logs.info(e.message)
            return JsonResponse(status=200, data={
                    "status": 400,
                    "message": "Enter Valid password",
            })
Esempio n. 42
0
def facebook_login(request):
    # facebook 로그인 버튼을 누르면 code를 반환한다.
    code = request.GET.get('code')

    def get_access_token(code):
        # access_token을 받아올 url
        access_token_url = 'https://graph.facebook.com/v2.10/oauth/access_token'

        # access_token에 요청을 보내고 다시 돌아올 url 설정 request.path이 리퀘스트를 받은 url을 반환한다 ex)/member/facebook_login/
        redirect_uri = '{}{}'.format(settings.SITE_URL, request.path)

        # access_token 요청하기 위해서는 페이스북 앱 id, 리다이렉트할 url, 페이스북 앱 secret key, code가 필요하다
        access_token_params = {
            'client_id': settings.FACEBOOK_APP_ID,
            'redirect_uri': redirect_uri,
            'client_secret': settings.FACEBOOK_SECRET_KEY,
            'code': code,
        }
        # requests로 access_token_url에 params로 access_token_params으로 요청
        response = requests.get(access_token_url, params=access_token_params)

        result = response.json()
        if 'access_token' in result:
            return result['access_token']
        elif 'error' in result:
            return result['error']['message']

    # 토큰을 디버그 하는 함수
    def debug_access_token(access_token):

        app_access_token = '{}|{}'.format(settings.FACEBOOK_APP_ID,
                                          settings.FACEBOOK_SECRET_KEY)

        debug_token_url = 'https://graph.facebook.com/debug_token'

        debug_token_params = {
            'input_token': access_token,
            'access_token': app_access_token
        }

        response = requests.get(debug_token_url, params=debug_token_params)

        result = response.json()

        if 'error' in result:
            raise DebugTokenException(result)
        else:
            return result

    # 오류를 출력하고 이점 URL로 리다이렉트
    def error_message_and_redirect_referer():
        error_message = 'Facebook login error'
        messages.error(request, error_message)

        # 이전 URL 로 리다이렉트
        return redirect(request.META['HTTP_REFERER'])

    # 유저 정보를 받아오는 함수
    def get_user_info(user_id, token):
        # user_id 를 url로 넣으면 user의 기본 정보만 들고 올 수 있음
        url_user_info = 'https://graph.facebook.com/v2.9/{user_id}'.format(
            user_id=user_id)
        url_user_info_params = {
            'access_token': token,
            'fields': ','.join([
                'id',
                'name',
                'email',
            ])
        }
        response = requests.get(url_user_info, params=url_user_info_params)
        result = response.json()
        return result

    if not code:
        return error_message_and_redirect_referer()

    try:
        access_token = get_access_token(code)
        debug_result = debug_access_token(access_token)
        print(debug_result)
        user_info = get_user_info(user_id=debug_result['data']['user_id'],
                                  token=access_token)
        user = MyUser.objects.get_or_create_facebook_user(user_info)

        django_login(request, user)
        return redirect('main')
    except GetAccessTokenException as e:
        print(e.code)
        print(e.message)
        return error_message_and_redirect_referer()
    except DebugTokenException as e:
        print(e.code)
        print(e.message)
        return error_message_and_redirect_referer()
Esempio n. 43
0
def facebook_login(request):
    # facebook_login view가 처음 호출될 때
    #   유저가 Facebook login dialog에서 로그인 후, 페이스북에서 우리 서비스(Consumer)쪽으로
    #   GET 파라미터를 이용해 'code'값을 전달해줌 (전달받는 주소는 위의 uri_redirect)
    # code= 값이 있을 때만 로그인을 허용
    code = request.GET.get('code')
    app_access_token = '{}|{}'.format(settings.FACEBOOK_APP_ID,
                                      settings.FACEBOOK_SECRET_CODE)

    # Exception을 상속받아 CustomException을 생성
    class GetAccessTokenException(Exception):
        def __init__(self, *args, **kwargs):
            error_dict = args[0]['data']['error']
            self.code = error_dict['code']
            self.message = error_dict['message']
            self.is_valid = error_dict['is_valid']
            self.scopes = error_dict['scopes']

    class DebugTokenException(Exception):
        def __init__(self, *args, **kwargs):
            error_dict = args[0]['data']['error']
            self.code = error_dict['code']
            self.message = error_dict['message']

    def add_message_and_redirect_referer():
        """
        페이스북 로그인 오류 메세지를 request에 추가하고 이전 페이지로 redirect
        :return: redirect
        """
        error_message_for_user = '******'
        messages.error(request, error_message_for_user)
        return redirect(request.META['HTTP_REFERER'])

    def get_access_token(code):
        """
        code를 받아 액세스토큰 교환 URL에 요청 이후 해당 액세스토큰을 반환
        오류 발생시 오류 메세지 리턴
        :param code:
        :return:
        """
        # facebook_login view가 처음 호출될 때 'code' request GET parameter를 받음
        # 액세스토큰의 코드교환할 url을 만들어준다.
        url_access_token = 'https://graph.facebook.com/v2.9/oauth/access_token'

        # 이전에 요청했던 redirect_uri와 같은 값을 만들어줌(access_token을 요청할 때 필요)
        redirect_uri = '{}://{}{}'.format(
            request.scheme,
            request.META['HTTP_HOST'],
            request.path,
        )
        # 액세스토큰의 코드 교환 - uri 생성을 위한 params
        url_access_token_params = {
            'client_id': settings.FACEBOOK_APP_ID,
            'redirect_uri': redirect_uri,
            'client_secret': settings.FACEBOOK_SECRET_CODE,
            'code': code,
        }
        # 해당 url에 get요청 후 결과(json형식)를 파이썬 object로 변환(result 변수)
        response = requests.get(url_access_token,
                                params=url_access_token_params)
        # 액세스 토큰 출력해보기
        result = response.json()
        # 좀더 깨끗하게 갖고오는 pprint메서드 사용
        # pprint(result)
        # {'access_token': 'EAAFGwwGAqT8BAND82fJLGNBAZAY9BMmiFL7zilPtTmZCZBBPFL5gEvHjkTGn4p9T3OGJ9A29oQrL6LW8EenN6GpirlWr7kYhZALVTFlQi0wkt8e8zzuiJyrCtH1u2UMdvh6ZB7jo1q2lDanZA9vdpFEZCRCOP1JviLjZAOUdEDpZCm67BbRRloOlB',
        #  'expires_in': 5179068,
        #  'token_type': 'bearer'}
        if 'access_token' in result:
            return result['access_token']
        elif 'error' in result:
            raise GetAccessTokenException(result)
        else:
            raise Exception('Unknown Error')

    def debug_token(token):
        url_debug_token = "https://graph.facebook.com/debug_token"
        url_debug_token_params = {
            'input_token': token,
            'access_token': app_access_token,
        }
        response = requests.get(url_debug_token, url_debug_token_params)
        result = response.json()
        if 'error' in result['data']:
            raise DebugTokenException(result)
        else:
            return result

    def get_user_info(user_id, token):
        url_user_info = 'https://graph.facebook.com/v2.9/{user_id}'.format(
            user_id=user_id)
        url_user_info_params = {
            'access_token':
            token,
            # 권한을 요청하지 않아도 오는 기본 정보
            # 반드시 scope 내용을 적어줘야한다.
            'fields':
            ','.join([
                'id',
                'name',
                'first_name',
                'last_name',
                'picture',
                'gender',
            ])
        }
        response = requests.get(url_user_info, params=url_user_info_params)
        result = response.json()
        return result

    # code 키값이 존재하지 않으면 로그인을 더이상 진행하지 않음.
    if not code:
        return add_message_and_redirect_referer()
    try:
        # 이 view에 GET parameter로 전달된 code를 사용해서 access_token을 받아옴
        # 성공시 access_token값을 가져옴
        # 실패시 GetAccessTokenException이 발생
        access_token = get_access_token(code)

        # 위에서 받아온 access_token을 이용해 debug_token을 요청
        # 성공시 토큰을 디버그한 결과 (user_id, scopes 등..)이 리턴
        # 실패시 DebugTokenException이 발생
        debug_result = debug_token(access_token)

        # debug_result에 있는 user_id값을 이용해서 GraphAPI에 유저정보를 요청
        user_info = get_user_info(user_id=debug_result['data']['user_id'],
                                  token=access_token)

        # 모델에서 UserManager의 메서드를 사용하여 유저정보 가져온다.
        user = User.objects.get_or_create_facebook_user(user_info)
        # 유저를 로그인시킨다.
        django_login(request, user)
        return redirect(request.META['HTTP_REFERER'])

    except GetAccessTokenException as e1:
        print('AccessToken Error code : ', e1.code)
        print('AccessToken Error msg : ', e1.message)
        return add_message_and_redirect_referer()
    except DebugTokenException as e2:
        print('Debug Error code : ', e2.code)
        print('Debug Error msg : ', e2.message)
        return add_message_and_redirect_referer()
Esempio n. 44
0
def login(request):
    user = authenticate(username=request.POST['username'], password=request.POST['password'])
    if user is not None:
        django_login(request, user)
    return render_to_response("templates/index.html", context_instance=RequestContext(request))
Esempio n. 45
0
def facebook_login(request):
    class AccessTokenInfo(NamedTuple):
        access_token: str
        token_type: str
        expires_in: str

    class DebugTokenInfo(NamedTuple):
        app_id: str
        application: str
        expires_at: int
        is_valid: bool
        issued_at: int
        scopes: list
        type: str
        user_id: str

    class UserInfo():
        def __init__(self, data):
            self.id = data['id']
            self.email = data.get('email', '')
            self.url_picture = data['picture']['data']['url']

    app_id = FACEBOOK_APP_ID
    app_secret_code = FACEBOOK_APP_SECRET_CODE
    app_access_token = f'{app_id}|{app_secret_code}'
    code = request.GET.get('code')

    def get_access_token_info(code):

        redirect_uri = '{scheme}://{host}{relative_url}'.format(
            scheme=request.scheme,
            host=request.META['HTTP_HOST'],
            relative_url=reverse('member:facebook_login'),
        )

        print('redirect_uri:', redirect_uri)
        url_access_token = 'https://graph.facebook.com/v2.10/oauth/access_token'
        params_access_token = {
            'client_id': app_id,
            'redirect_uri': redirect_uri,
            'client_secret': app_secret_code,
            'code': code,
        }
        response = requests.get(url_access_token, params_access_token)

        return AccessTokenInfo(**response.json())

    def get_debug_token_info(token):
        url_debug_token = 'https://graph.facebook.com/debug_token'
        params_debug_token = {
            'input_token': access_token,
            'access_token': app_access_token,
        }
        response = requests.get(url_debug_token, params_debug_token)
        return DebugTokenInfo(**response.json()['data'])

    access_token_info = get_access_token_info(code)

    access_token = access_token_info.access_token

    debug_token_info = get_debug_token_info(access_token)

    user_info_fields = {
        'id',
        'name',
        'picture',
        'email',
    }
    url_graph_user_info = 'https://graph.facebook.com/me'
    params_graph_user_info = {
        'fields': ','.join(user_info_fields),
        'access_token': access_token,
    }
    response = requests.get(url_graph_user_info, params_graph_user_info)
    result = response.json()
    user_info = UserInfo(data=result)

    username = f'fb_{user_info.id}'
    # 위 username에 해당하는 User가 있는지 검사
    if User.objects.filter(username=username).exists():
        # 있으면 user에 해당 유저를 할당
        user = User.objects.get(username=username)
    else:
        # 없으면 user에 새로 만든 User를 할당
        user = User.objects.create_user(
            user_type=User.USER_TYPE_FACEBOOK,
            username=username,
            age=0
        )
    # 유저를 로그인 시킴
    django_login(request, user)
    return redirect('post:post_list')
Esempio n. 46
0
def signup_oauth(request):
    if 'oauth_email' not in request.session \
       or 'oauth_firstname' not in request.session \
       or 'oauth_lastname' not in request.session:
        return HttpServerError(request, 'Invalid redirect received')

    if request.method == 'POST':
        # Second stage, so create the account. But verify that the
        # nonce matches.
        data = request.POST.copy()
        data['email'] = request.session['oauth_email'].lower()
        data['first_name'] = request.session['oauth_firstname']
        data['last_name'] = request.session['oauth_lastname']
        form = SignupOauthForm(data=data)
        if form.is_valid():
            log.info(
                "Creating user for {0} from {1} from oauth signin of email {2}"
                .format(form.cleaned_data['username'], get_client_ip(request),
                        request.session['oauth_email']))

            user = User.objects.create_user(
                form.cleaned_data['username'].lower(),
                request.session['oauth_email'].lower(),
                last_login=datetime.now())
            user.first_name = request.session['oauth_firstname']
            user.last_name = request.session['oauth_lastname']
            user.password = OAUTH_PASSWORD_STORE
            user.save()

            # Clean up our session
            del request.session['oauth_email']
            del request.session['oauth_firstname']
            del request.session['oauth_lastname']
            request.session.modified = True

            # We can immediately log the user in because their email
            # is confirmed.
            user.backend = settings.AUTHENTICATION_BACKENDS[0]
            django_login(request, user)

            # Redirect to the sessions page, or to the account page
            # if none was given.
            return HttpResponseRedirect(
                request.session.pop('login_next', '/account/'))
    elif 'do_abort' in request.GET:
        del request.session['oauth_email']
        del request.session['oauth_firstname']
        del request.session['oauth_lastname']
        request.session.modified = True
        return HttpResponseRedirect(request.session.pop('login_next', '/'))
    else:
        # Generate possible new username
        suggested_username = request.session['oauth_email'].replace('@',
                                                                    '.')[:30]

        # Auto generation requires firstname and lastname to be specified
        f = request.session['oauth_firstname'].lower()
        l = request.session['oauth_lastname'].lower()
        if f and l:
            for u in itertools.chain([
                    "{0}{1}".format(f, l[0]),
                    "{0}{1}".format(f[0], l),
            ], ("{0}{1}{2}".format(f, l[0], n) for n in range(100))):
                if not User.objects.filter(username=u[:30]).exists():
                    suggested_username = u[:30]
                    break

        form = SignupOauthForm(
            initial={
                'username': suggested_username,
                'email': request.session['oauth_email'].lower(),
                'first_name': request.session['oauth_firstname'][:30],
                'last_name': request.session['oauth_lastname'][:30],
            })

    return render_pgweb(
        request, 'account', 'account/signup_oauth.html', {
            'form': form,
            'operation': 'New account',
            'savebutton': 'Sign up for new account',
            'recaptcha': True,
        })
Esempio n. 47
0
 def login(self, request, user):
     token, _ = Token.objects.get_or_create(user=user)
     django_login(request, user)
     return {'user': user, 'token': token}
Esempio n. 48
0
def auth_receive(request):
    if 's' in request.GET and request.GET['s'] == "logout":
        # This was a logout request
        return HttpResponseRedirect('/')

    if 'i' not in request.GET:
        return HttpResponse("Missing IV in url!", status=400)
    if 'd' not in request.GET:
        return HttpResponse("Missing data in url!", status=400)

    # Set up an AES object and decrypt the data we received
    decryptor = AES.new(base64.b64decode(settings.PGAUTH_KEY), AES.MODE_CBC,
                        base64.b64decode(str(request.GET['i']), "-_"))
    s = decryptor.decrypt(base64.b64decode(str(request.GET['d']),
                                           "-_")).rstrip(' ')

    # Now un-urlencode it
    try:
        data = parse_qs(s, strict_parsing=True)
    except ValueError:
        return HttpResponse("Invalid encrypted data received.", status=400)

    # Check the timestamp in the authentication
    if int(data['t'][0]) < time.time() - 10:
        return HttpResponse("Authentication token too old.", status=400)

    # Update the user record (if any)
    try:
        user = User.objects.get(username=data['u'][0])
        # User found, let's see if any important fields have changed
        changed = False
        if user.first_name != data['f'][0]:
            user.first_name = data['f'][0]
            changed = True
        if user.last_name != data['l'][0]:
            user.last_name = data['l'][0]
            changed = True
        if user.email != data['e'][0]:
            user.email = data['e'][0]
            changed = True
        if changed:
            user.save()
    except User.DoesNotExist:
        # User not found, create it!
        user = User(
            username=data['u'][0],
            first_name=data['f'][0],
            last_name=data['l'][0],
            email=data['e'][0],
            password='******',
        )
        user.save()

    # Ok, we have a proper user record. Now tell django that
    # we're authenticated so it persists it in the session. Before
    # we do that, we have to annotate it with the backend information.
    user.backend = "%s.%s" % (AuthBackend.__module__, AuthBackend.__name__)
    django_login(request, user)

    # Finally, redirect the user
    if 'su' in data.has_key:
        return HttpResponseRedirect(data['su'][0])
    # No redirect specified, see if we have it in our settings
    if hasattr(settings, 'PGAUTH_REDIRECT_SUCCESS'):
        return HttpResponseRedirect(settings.PGAUTH_REDIRECT_SUCCESS)
    return HttpResponse(
        "Authentication successful, but don't know where to redirect!",
        status=500)
Esempio n. 49
0
def login(request):
    #add bot url
    #https://discordapp.com/api/oauth2/authorize?client_id=416470490475921418&permissions=142336&redirect_uri=http%3A%2F%2Fbabelfish099.pythonanywhere.com%2Flogin%2F&response_type=code&scope=bot%20guilds%20email
    context = {
        "page_view": "Login",
    }
    if request.method == "POST":
        #post returns JSON, not a page
        response = {
            'errors': [],
            'success': False,
        }
        if request.user.is_authenticated:
            response['success'] = True
        else:
            if request.POST.get("password2"):  #Register
                email = request.POST.get('email')
                raw_password1 = request.POST.get('password')
                raw_password2 = request.POST.get('password2')
                if raw_password2 != raw_password1:
                    response["errors"].append("Passwords do not match.")
                elif len(raw_password1) < 8:
                    response["errors"].append("Password is too short.")
                else:
                    user, created = User.objects.get_or_create(username=email,
                                                               email=email)
                    if not created:
                        response["errors"].append(
                            "That email already has an account associated with it."
                        )
                    else:
                        user.set_password(raw_password1)
                        user.save()
                        with UserContext(user):
                            user_profile = UserProfile(user_id=user.id, )
                            user_profile.save()
                        django_login(request, user)
                        response['success'] = True
            else:  #login
                username = request.POST.get('email')
                raw_password = request.POST.get('password')
                user = authenticate(username=username, password=raw_password)
                if user is not None:
                    django_login(request, user)
                    response['success'] = True
                else:
                    response["errors"].append("Invalid username or password.")

        response = json.dumps(response)
        return HttpResponse(response)
    else:
        if request.user.is_authenticated:
            return redirect("/")

        #Handle discord login
        if request.GET.get("code"):
            user, error = discord.login_and_link(request)
            if not user:
                context[
                    'error'] = error  #"Problem logging in with Discord. If you already have an account login first to connect it with Discord."
                return render(request, "pages/base.html", context)
            else:
                django_login(request, user)
                return redirect("/")
        return render(request, "pages/base.html", context)
Esempio n. 50
0
def login(request):
    # member/login.html 생성
    #   username, password, button이 있는 HTML생성
    #   POST요청이 올 경우 좌측 코드를 기반으로 로그인 완료 후 post_list로 이동
    #   실패할경우 HttpResponse로 'Login invalid!'띄워주기

    # member/urls.py생성
    #   /member/login/으로 접근시 이 view로 오도록 설정
    #   config/urls.py에 member/urls.py를 include
    #       member/urls.py에 app_name설정으로 namespace지정

    # POST요청이 왔을 경우
    if request.method == 'POST':
        ### Form클래스 미사용시
        # 요청받은 POST데이터에서 username, password키가 가진 값들을
        # username, password변수에 할당 (문자열)
        # username = request.POST['username']
        # password = request.POST['password']

        # authenticate함수를 사용해서 User객체를 얻어 user에 할당
        # 인증에 실패할 경우 user변수에는 None이 할당됨
        # user = authenticate(
        #     request,
        #     username=username,
        #     password=password
        # )
        # user변수가 None이 아닐 경우 (정상적으로 인증되어 User객체를 얻은 경우)
        # if user is not None:
        #     # Django의 session을 이용해 이번 request와 user객체를 사용해 로그인 처리
        #     # 이후의 request/response에서는 사용자가 인증된 상태로 통신이 이루어진다
        #     django_login(request, user)
        #     # 로그인 완료후에는 post_list뷰로 리다이렉트 처리
        #     return redirect('post:post_list')

        ### Form클래스 사용시
        #   Bound form생성
        form = LoginForm(data=request.POST)
        # Bound form의 유효성을 검증
        #   https://docs.djangoproject.com/en/1.11/topics/forms/#building-a-form-in-django
        if form.is_valid():
            user = form.cleaned_data['user']
            django_login(request, user)
            # 일반적인 경우에는 post_list로 이동하지만,
            # GET parameter의 next속성값이 있을 경우 해당 URL로 이동
            next = request.GET.get('next')
            if next:
                return redirect(next)
            return redirect('post:post_list')
    # GET요청이 왔을 경우 (단순 로그인 Form보여주기)
    else:
        # 만약 이미 로그인 된 상태일 경우에는
        # post_list로 redirect
        # 아닐경우 login.html을 render해서 리턴
        if request.user.is_authenticated:
            return redirect('post:post_list')
        # LoginForm인스턴스를 생성해서 context에 넘김
        form = LoginForm()
    context = {
        'form': form,
    }
    # render시 context에는 LoginForm클래스형 form객체가 포함됨
    return render(request, 'member/login.html', context)
Esempio n. 51
0
def facebook_login(request):
    class AccessTokenInfo(NamedTuple):
        access_token: str
        token_type: str
        expires_in: str

    class DebugTokenInfo(NamedTuple):
        app_id: str
        application: str
        expires_at: int
        is_valid: bool
        issued_at: int
        scopes: list
        type: str
        user_id: str

    class UserInfo:
        def __init__(self, data):
            self.id = data['id']
            self.email = data.get('email', '')
            self.url_picture = data['picture']['data']['url']

    app_id = settings.FACEBOOK_APP_ID
    app_secret_code = settings.FACEBOOK_APP_SECRET_CODE
    app_access_token = f'{app_id}|{app_secret_code}'
    code = request.GET.get('code')

    def get_access_token_info(code_value):
        # 사용자가 페이스북에 로그인하기 위한 링크에 있던 'redirect_uri' GET파라미터의 값과 동일한 값
        redirect_uri = '{scheme}://{host}{relative_url}'.format(
            scheme=request.scheme,
            host=request.META['HTTP_HOST'],
            relative_url=reverse('view:member:facebook_login'),
        )
        print('redirect_uri:', redirect_uri)
        # 액세스 토큰을 요청하기 위한 엔드포인트
        url_access_token = 'https://graph.facebook.com/v2.10/oauth/access_token'
        # 액세스 토큰 요청의 GET파라미터 목록
        params_access_token = {
            'client_id': app_id,
            'redirect_uri': redirect_uri,
            'client_secret': app_secret_code,
            'code': code_value,
        }
        # 요청 후 결과를 받아옴
        response = requests.get(url_access_token, params_access_token)
        # 결과는 JSON형식의 텍스트이므로 아래와 같이 사용
        # json.loads(response.content) 와 같음

        # AccessTokenInfo(access_token=response.json()['access_token'],
        #    'token_type'=response.json()['token_type.....
        return AccessTokenInfo(**response.json())

    def get_debug_token_info(token):
        url_debug_token = 'https://graph.facebook.com/debug_token'
        params_debug_token = {
            'input_token': token,
            'access_token': app_access_token,
        }
        response = requests.get(url_debug_token, params_debug_token)
        return DebugTokenInfo(**response.json()['data'])

    # 전달받은 code값으로 AccessTokenInfo namedtuple을 반환
    access_token_info = get_access_token_info(code)
    # namedtuple에서 'access_token'속성의 값을 가져옴
    access_token = access_token_info.access_token
    # DebugTokenInfo 가져오기
    debug_token_info = get_debug_token_info(access_token)

    # 유저정보 가져오기
    user_info_fields = [
        'id',
        'name',
        'picture',
        'email',
    ]
    url_graph_user_info = 'https://graph.facebook.com/me'
    params_graph_user_info = {
        'fields': ','.join(user_info_fields),
        'access_token': access_token,
    }
    response = requests.get(url_graph_user_info, params_graph_user_info)
    result = response.json()
    user_info = UserInfo(data=result)

    # 페이스북으로 가입한 유저의 username
    #   fb_<facebook_user_id>
    username = f'fb_{user_info.id}'
    # 위 username에 해당하는 User가 있는지 검사
    if not User.objects.filter(username=username).exists():
        # 없으면 user에 새로 만든 User를 할당
        User.objects.create_user(user_type=User.USER_TYPE_FACEBOOK,
                                 username=username,
                                 age=0)
    # user를 로그인시키고 post_list페이지로 이동
    user = authenticate(facebook_user_id=user_info.id)
    django_login(request, user)
    return redirect('post:post_list')
Esempio n. 52
0
def signup(request):
    if (request.method == 'POST'):

        username = request.POST['username']
        firstname = request.POST['firstname']
        lastname = request.POST['lastname']
        email = request.POST['email']
        password = request.POST['password']
        cnfpassword = request.POST['cnfpassword']

        users = User.objects.filter(username=username)

        f = 0

        if (users):
            f = 1

        emails = User.objects.filter(email=email)

        if (emails):
            f = 2

        if cnfpassword == password:

            if (f == 0):

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

                # send_mail(subject, message, from_email, to_list, fail_silently=True)

                subject = "Thank you for signing up with Resource Sharing Portal"
                message = "Hi "+user.first_name+" "+user.last_name + \
                    ",\nWelcome to Resources Sharing Portal!\nWe are Excited to serve you with the resources you are looking for."
                from_email = settings.EMAIL_HOST_USER
                to_list = [user.email, settings.EMAIL_HOST_USER]

                send_mail(subject,
                          message,
                          from_email,
                          to_list,
                          fail_silently=True)

                django_login(request, user)

                messages.success(
                    request, "Successfully Logged In as " + user.username + "")
                return redirect("/")

            elif (f == 1):

                messages.error(
                    request,
                    'Username already exists please enter a different username'
                )
                return redirect("/")

            else:
                messages.error(
                    request,
                    'Email already registered Please enter a different Email Address'
                )
                return redirect("/")

        else:
            messages.error(
                request, 'Password and Confirm Password Fields should match')
            return redirect("/")
Esempio n. 53
0
def password_reset(request, is_admin_site=False,
                   template_name='registration/password_reset_form.html',
                   email_template_name='registration/password_reset_email.html',
                   subject_template_name='registration/password_reset_subject.txt',
                   password_reset_form=PasswordResetForm,
                   token_generator=default_token_generator,
                   post_reset_redirect=None,
                   from_email=None,
                   extra_context=None,
                   html_email_template_name=None,
                   extra_email_context=None):

    formlogin=AuthenticationForm()
    form = password_reset_form()

    if post_reset_redirect is None:
        post_reset_redirect = reverse('password_reset_done')
    else:
        post_reset_redirect = resolve_url(post_reset_redirect)
    if request.method == 'POST' and 'loginbtn' in request.POST:
        formlogin = AuthenticationForm(data=request.POST)
        if formlogin.is_valid():
            user = authenticate(email=request.POST['email'], password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                else:
                    return redirect("/login")
            else:
                return redirect("/login")

    elif request.method == "POST":
        formlogin=AuthenticationForm()
        form = password_reset_form(request.POST)
        if form.is_valid():
            opts = {
                'use_https': request.is_secure(),
                'token_generator': token_generator,
                'from_email': from_email,
                'email_template_name': email_template_name,
                'subject_template_name': subject_template_name,
                'request': request,
                'html_email_template_name': html_email_template_name,
                'extra_email_context': extra_email_context,
            }
            if is_admin_site:
                warnings.warn(
                    "The is_admin_site argument to "
                    "django.contrib.auth.views.password_reset() is deprecated "
                    "and will be removed in Django 1.10.",
                    RemovedInDjango110Warning, 3
                )
                opts = dict(opts, domain_override=request.get_host())
            form.save(**opts)
            return HttpResponseRedirect(post_reset_redirect)
    else:
        form = password_reset_form()
    context = {
        'form': form,
        'title': _('Password reset'),
        'formlogin': formlogin

    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)
Esempio n. 54
0
def registration(request):
    """
    A form to allow for registration of new users
    """

    # If global user registration is deactivated, redirect
    if not settings.WGER_SETTINGS['ALLOW_REGISTRATION']:
        return HttpResponseRedirect(reverse('software:features'))

    template_data = {}
    template_data.update(csrf(request))

    # Don't show captcha if the global parameter is false
    FormClass = RegistrationForm if settings.WGER_SETTINGS['USE_RECAPTCHA'] \
        else RegistrationFormNoCaptcha

    # Redirect regular users, in case they reached the registration page
    if request.user.is_authenticated and not request.user.userprofile.is_temporary:
        return HttpResponseRedirect(reverse('core:dashboard'))

    if request.method == 'POST':
        form = FormClass(data=request.POST)

        # If the data is valid, log in and redirect
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            email = form.cleaned_data['email']
            user = User.objects.create_user(username, email, password)
            user.save()

            # Pre-set some values of the user's profile
            language = Language.objects.get(
                short_name=translation.get_language())
            user.userprofile.notification_language = language

            # Set default gym, if needed
            gym_config = GymConfig.objects.get(pk=1)
            if gym_config.default_gym:
                user.userprofile.gym = gym_config.default_gym

                # Create gym user configuration object
                config = GymUserConfig()
                config.gym = gym_config.default_gym
                config.user = user
                config.save()

            user.userprofile.save()

            user = authenticate(username=username, password=password)
            django_login(request, user)
            messages.success(request, _('You were successfully registered'))
            return HttpResponseRedirect(reverse('core:dashboard'))
    else:
        form = FormClass()

    template_data['form'] = form
    template_data['title'] = _('Register')
    template_data['extend_template'] = 'base.html'

    return render(request, 'form.html', template_data)
Esempio n. 55
0
def login_get_access(request):
    print '*********** login_get_access ************'
    if 'state' not in request.session:
        request.session['state'] = 'blah123'  # 'state'
    if request.GET['state'] != request.session['state']:
        return HttpResponseRedirect('/')
    data = {
        'client_id': client_id_login,
        'client_secret': client_secret_login,
        'code': request.GET['code'],
        'redirect_uri': host  # host+'/add_hook'
    }
    res = requests.post('https://github.com/login/oauth/access_token',
                        data=data)
    atts = res.text.split('&')
    d = {}
    try:
        for att in atts:
            keyv = att.split('=')
            d[keyv[0]] = keyv[1]
        access_token = d['access_token']
        request.session['access_token'] = access_token
        print 'access_token: ' + access_token
    except Exception as e:
        print "exception: " + str(e)
        print "no access token"
        print "response: %s" % res.text
        return HttpResponseRedirect('/')

    g = Github(access_token)
    email = g.get_user().email
    username = g.get_user().login
    if email == '' or type(email) == type(None):
        return render(
            request, 'msg.html',
            {'msg': 'You have to make you email public and try again'})
    request.session['avatar_url'] = g.get_user().avatar_url
    print 'avatar_url: ' + request.session['avatar_url']
    try:
        user = OUser.objects.get(email=email)
        user.username = username
        user.backend = 'mongoengine.django.auth.MongoEngineBackend'
        user.save()
    except:
        try:
            user = OUser.objects.get(username=username)
            user.email = email
            user.backend = 'mongoengine.django.auth.MongoEngineBackend'
            user.save()
        except:
            print '<%s,%s>' % (email, username)
            sys.stdout.flush()
            sys.stderr.flush()
            # The password is never important but we set it here because it is required by User class
            user = OUser.create_user(username=username,
                                     password=request.session['state'],
                                     email=email)
            user.backend = 'mongoengine.django.auth.MongoEngineBackend'
            user.save()
    django_login(request, user)
    print 'access_token: ' + access_token
    sys.stdout.flush()
    sys.stderr.flush()
    return HttpResponseRedirect('/')
Esempio n. 56
0
 def perform_login(request, user):
     token, created = Token.objects.get_or_create(user=user)
     django_login(request, user)
     return token
Esempio n. 57
0
 def form_valid(self, form):
     """Security check complete. Log the user in."""
     django_login(self.request, form.get_user())
     return _login_success_redirect(self.request, form.get_user(),
                                    self.get_redirect_url())
Esempio n. 58
0
def register(request):
    if request.user.is_authenticated():
        return redirect('/')
    registration_form = RegistrationForm()
    formlogin=AuthenticationForm()
    if request.method == 'POST' and 'loginbtn' in request.POST:
        formlogin = AuthenticationForm(data=request.POST)
        if formlogin.is_valid():
            user = authenticate(email=request.POST['email'], password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    return redirect('/')
                else:
                    return redirect("/login")
            else:
                return redirect("/login")
    if request.method == 'POST':
        form = RegistrationForm(data=request.POST)
        if form.is_valid():
            datas={}
            datas['email']=form.cleaned_data['email']
            datas['password1']=form.cleaned_data['password1']
            datas['voornaam']=form.cleaned_data['voornaam']
            datas['naam']=form.cleaned_data['naam']
            #We will generate a random activation key
            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            emailsalt = datas['email']
            if isinstance(emailsalt, unicode):
                emailsalt = emailsalt.encode('utf8')
            datas['activation_key']=hashlib.sha1(salt+emailsalt).hexdigest()

            datas['activation_email']=request.build_absolute_uri('/').strip("/") + '/activate/' + datas['activation_key']
            datas['email_path']="webapp/activation/ActivationEmail.html"
            datas['email_subject']="Welkom bij ViaSofie"

            ctx = {
                'voornaam': datas['voornaam'],
                'naam': datas['naam'],
                'activation_link': datas['activation_email']
            }

            message = get_template(datas['email_path']).render(Context(ctx))

            try:
                msg = EmailMessage(datas['email_subject'], message, '*****@*****.**', [datas['email']])
                msg.content_subtype = "html"
                msg.send()
            except BadHeaderError:
                return HttpResponse("invalid.")

            # form.sendEmail(datas) #Send validation email
            form.save(datas) #Save the user and his profile

            request.session['registered']=True #For display purposes
            return redirect('/')
        else:
            registration_form = form #Display form with error messages (incorrect fields, etc)
    else:
    	form = RegistrationForm()
    return render(request, 'webapp/register.html', locals())
Esempio n. 59
0
 def login(self):
     self.user = self.serializer.validated_data['user']
     self.token, created = Token.objects.get_or_create(user=self.user)
     django_login(self.request, self.user)
Esempio n. 60
0
def admin_login(request):
    line_id = request.session['line_id']
    user = get_user_model().objects.get(username=line_id)
    django_login(request, user)
    return redirect("/kami")