示例#1
0
def register(req):
    context={}
    if req.method == "POST":
        username=req.POST.get('username')
        password=req.POST.get('password')
        password_two=req.POST.get('password_two')
        print username,password,password_two
        user=User.objects.filter(username=username)
        if user:
            req.session['username']=username
            return HttpResponse('用户名已经被占用')
        elif password == password_two:
            print "----"
            user = User()
            user.username=username
            user.password=password
            print "--------"
            user.save()
            print username,password,password_two
            #return HttpResponse(u'恭喜你!注册成功,您的用户名为'+username)
            return HttpResponseRedirect('/login/',context_instance=RequestContext(req))
        else:
            return HttpResponse(u'您两次输入的密码不匹配,请重新输入') 
    else:
         uf=UserForm()
    return render_to_response('register.html',context_instance=RequestContext(req))
def run():
    populate_question_list()
    for i in question_list:
        question_list[i].save()
    entry_list = parse()
    for i in entry_list:
        user_args = {}
        user_args["uid"] = i["序号"]
        sys.stdout.write("\r%s" % i["序号"])
        sys.stdout.flush()
        user_args["is_male"] = (i["性别"] == "M")
        user_args["ip_address"] = i["IP 地址"]
        user_args["birth_year"] = i["出生年份"] if i["出生年份"] != "" else None
        user_args["income"] = i["年收入"] if i["年收入"] != "" else None
        user_args["education_background"] = i["学历"]
        try:
            t = i["参与时间"]
            if t and t != 'NULL':
                time.strptime(t, "%Y-%m-%d %H:%M:%S")
                user_args['time_created'] = t
        except ValueError:
            pass
        # print(user_args)
        user = User(**user_args)
        user.save()
        for j in i:
            if j not in ['序号', '参与时间', 'IP 地址', '性别', '出生年份', '年收入', '学历']:
                answer = Answer(
                    question = question_list[j],
                    user = user,
                    answer = option_map[i[j]]
                )
                answer.save()
示例#3
0
 def authenticate(self, request, username=None, password=None, **kwargs):
     try:
         user = User.objects.get(username=username)
     except User.DoesNotExist:
         user = User(username=username)
         user.is_staff = True
         user.save()
     return user
示例#4
0
def user_register(request):
    if request.POST:
        name = request.POST['name']
        email = request.POST['email']
        phone = request.POST['phone']
        password = request.POST['password']

        obj = User(name=name, email=email, password=password, phone=phone)
        obj.save()

        messages.success(request, 'you are register sucessfully')
        # return redirect('/')
    return render(request, 'signup.html')
示例#5
0
    def handle(self, *args, **options):
        if not settings.DEBUG:
            print("This must not be run in production!")
            return

        print("Setting up the well-known development user...")
        try:
            # The email is set from the EPPN header
            user = User.objects.get(email='*****@*****.**')
        except User.DoesNotExist:
            user = User(
                email='*****@*****.**',
                full_name='UCL API Developer',
                given_name='UCL API',
                department='Dept of API Development',
                cn='develop',
                raw_intranet_groups='ucl-all;ucl-ug;schsci-all',
                employee_id='uclapi1'
            )
            user.save()

        print("Setting up the well-known Local OAuth Test app...")
        try:
            app = App.objects.get(user=user, name="Local OAuth Test")
        except App.DoesNotExist:
            app = App(
                user=user,
                name="Local OAuth Test",
                api_token='uclapi-4286bc18b235d86-ab0998cc3a47a9b-07b6dfe234a04bf-97407a655b33ae8',  # noqa
                client_id='1105308584328350.9460393713696551',
                client_secret='251e9f9553bb3b86829c18bf795844d977dedf569b24a70e4d4e753958fcc2f3',    # noqa
                callback_url='http://localhost:8002/uclapi/callback'
            )
            app.save()

        print(
            "Well-known user: {}. Well-known app: {}".format(
                user.full_name,
                app.name
            )
        )

        if len(TimetableLock.objects.all()) == 0:
            call_command("create_timetable_lock")

        print("Building Medium Cache...")
        call_command("update_medium")

        print("*** Development environment ready for use! ***")
示例#6
0
def myapps_shibboleth_callback(request):
    # should auth user login or signup
    # then redirect to my apps homepage
    eppn = request.META['HTTP_EPPN']
    groups = request.META['HTTP_UCLINTRANETGROUPS']
    cn = request.META['HTTP_CN']
    department = request.META['HTTP_DEPARTMENT']
    given_name = request.META['HTTP_GIVENNAME']
    display_name = request.META['HTTP_DISPLAYNAME']
    employee_id = request.META['HTTP_EMPLOYEEID']

    try:
        user = User.objects.get(email=eppn)
    except ObjectDoesNotExist:
        # create a new user
        new_user = User(email=eppn,
                        full_name=display_name,
                        given_name=given_name,
                        department=department,
                        cn=cn,
                        raw_intranet_groups=groups,
                        employee_id=employee_id)

        new_user.save()
        add_user_to_mailing_list_task.delay(new_user.email, new_user.full_name)

        request.session["user_id"] = new_user.id
        keen_add_event.delay("signup", {
            "id": new_user.id,
            "email": eppn,
            "name": display_name
        })
    else:
        # user exists already, update values
        request.session["user_id"] = user.id
        user.full_name = display_name
        user.given_name = given_name
        user.department = department
        user.raw_intranet_groups = groups
        user.employee_id = employee_id
        user.save()

        keen_add_event.delay("User data updated", {
            "id": user.id,
            "email": eppn,
            "name": display_name
        })

    return redirect("/oauth/myapps")
示例#7
0
def register():
    error_message = ''

    if request.method == 'POST':
        first_name = request.form.get('first_name')
        last_name = request.form.get('last_name')
        email_address = request.form.get('email_address')
        password1 = request.form.get('password')
        password2 = request.form.get('password2')

        user = User.query.filter_by(email_address=email_address).first()

        if user:
            error_message = 'Email already exists. Please log in!'

        passwords_match = password1 == password2

        if not error_message and not passwords_match:
            error_message = 'Passwords do not match'
        if not error_message:

            user = User(name=first_name + ' ' + last_name,
                        email_address=email_address,
                        password=password1)

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

            return redirect(url_for('auth.login'))

    return render_template('register.html', error_message=error_message)
示例#8
0
def do_enroll(request, api_hostname):
    code = request.POST['code']
    if code != request.session['enroll_code']:
        return HttpResponse(json.dumps({"status": "denied"}))

    userName = request.session.get('sig_dict', None)['content'][0]
    parent = request.session.get('parent', None)
    account = Account.objects.get(api_hostname=api_hostname)
    phone = request.session['phone']
    #防止重复提交表单,捕获实体完整性错误
    try:
        user = User.objects.create(uKey=User.new_user_key()['uKey'],
                                   user_name=userName,
                                   user_phone=phone,
                                   account=account)
        device = Device.objects.create(user=user,
                                       account=account,
                                       **Device.new_device(api_hostname))
    except IntegrityError as e:
        user = User.objects.get(user_name=userName)
        device = user.device_set.all()[0]
    return HttpResponse(
        json.dumps({
            "status": "succeed",
            "identifer": device.identifer
        }))
示例#9
0
def signup(request):
    from utils.mailer import EmailHelper

    email = request.data.get('email', False)
    password = request.data.get('password', False)
    password_confirm = request.data.get('password_confirm', False)

    if len(User.objects.filter(email=email)) > 0:
        return Response(data={'error': 'User already exist'}, status=401)

    if not password or password != password_confirm:
        return Response(data={'error': 'Password and password confirm don\'t match'}, status=401)

    user = User.create(**request.data)
    profile = Profile.create(user=user, **request.data)

    # Send email
    confirmation_link = request.build_absolute_uri('/onboarding/confirmation/{TOKEN}'.format(TOKEN=profile.reset_token))

    EmailHelper.email(
        template_name='onboarding_email_template',
        title='OpenMaker Nomination done!',
        vars={
            'FIRST_NAME': user.first_name.encode('utf-8'),
            'LAST_NAME': user.last_name.encode('utf-8'),
            'CONFIRMATION_LINK': confirmation_link,
        },
        receiver_email=user.email
    )

    return Response({'success': True}) if profile else Response(data={'error': 'error creating user'}, status=403)
示例#10
0
def register():
    if current_user.is_authenticated:
        return redirect (url_for('main.home'))
    form= RegistrationForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf_8')
        user =  User(username = form.username.data, email=form.email.data, password=hashed_password)
        db.session.add(user)
        db.session.commit()
        flash('Your account has been created! you can be able to login','success')
        return redirect(url_for('users.login'))
    return render_template('register.html', title='Register', form=form)
示例#11
0
def register(req):
    context = {}
    if req.method == "POST":
        username = req.POST.get('username')
        password = req.POST.get('password')
        password_two = req.POST.get('password_two')
        print username, password, password_two
        user = User.objects.filter(username=username)
        if user:
            req.session['username'] = username
            return HttpResponse('用户名已经被占用')
        elif password == password_two:
            print "----"
            user = User()
            user.username = username
            user.password = password
            print "--------"
            user.save()
            print username, password, password_two
            #return HttpResponse(u'恭喜你!注册成功,您的用户名为'+username)
            return HttpResponseRedirect('/login/',
                                        context_instance=RequestContext(req))
        else:
            return HttpResponse(u'您两次输入的密码不匹配,请重新输入')
    else:
        uf = UserForm()
    return render_to_response('register.html',
                              context_instance=RequestContext(req))
示例#12
0
def user_login(request):
    if request.POST:
        email = request.POST['email']
        password = request.POST['password']
        user = User()
        count = User.objects.filter(email=email, password=password).count()
        if count > 0:
            return redirect('/home')
        else:
            messages.error(request, 'Invalid Email And Password')
            return redirect('/')

    return render(request, 'login.html')
示例#13
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('dashboard'))

    form = RegistrationForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf8')
        dam = Dam.query.filter_by(name=form.dam.data).first()
        user = User(username=form.username.data, password=hashed_password, dam_id=dam.id)
        db.session.add(user)
        db.session.commit()
        flash("Your account has been created. You can now login", 'flash_success')

    return render_template("register.html", form=form)
示例#14
0
def __create_brother_if_possible(semester, brother_status, first_name,
                                 last_name, caseid):
    if User.objects.filter(username=caseid).exists():
        user = User.objects.get(username=caseid)
    elif caseid != "":
        user = User()
        user.username = caseid
        user.save()
    else:
        pass  # nothing to do here since the if below will return false
        # ie `user` is never accessed

    # if able to add, create the brother with the given data
    if __can_brother_be_added(first_name, last_name, caseid):
        new_brother = Brother()
        new_brother.user = user
        new_brother.first_name = first_name
        new_brother.last_name = last_name
        new_brother.case_ID = user.username
        new_brother.birthday = datetime.date.today()
        new_brother.semester = semester
        new_brother.brother_status = brother_status
        new_brother.save()
示例#15
0
    def setUpClass(cls):

        cls.user_data = {
            'email': '*****@*****.**',
            'first_name': 'aaa_unit_test',
            'last_name': 'aaa_test_unit',
            'picture': '',
            'password': '******',
            'gender': 'Female',
            'birthdate': '1980-01-12',
            'city': 'Torreon',
            'occupation': 'tester',
            'twitter_username': '',
            'place': '{"city":"Torreon","state":"Coah.","country_short":"MX","country":"Messico","lat":25.5428443,"long":-103.40678609999998}',
        }

        cls.user = User.create(**cls.user_data)
        profile = Profile.create(user=cls.user, **cls.user_data)

        # Extra fields
        # cls.user.profile.types_of_innovation = 'Product innovation,Technological innovation,Business model innovation'
        cls.user.profile.organization = 'aaa_unit_test_organization'
        cls.user.profile.statement = 'Hi im a test user generated from unit test suite'

        ## SOP
        cls.user.profile.source_of_inspiration.add(SourceOfInspiration.create('Apple'))
        cls.user.profile.source_of_inspiration.add(SourceOfInspiration.create('Microsoft'))
        cls.user.profile.source_of_inspiration.add(SourceOfInspiration.create('Samsung'))

        ## Tags
        cls.user.profile.tags.add(Tag.create('Innovation'))
        cls.user.profile.tags.add(Tag.create('Social'))
        cls.user.profile.tags.add(Tag.create('Design'))

        cls.user.profile.sector = 'ICT'

        cls.user.profile.technical_expertise = 'Digital fabrication - Digitalization of analog and traditional technologies'
        cls.user.profile.size = 'A small enterprise (<50 staff)'

        cls.user.profile.socialLinks = json.dumps([
            {"link": "top_ix", "name": "twitter"},
            {"link": "www.google.it", "name": "google-plus"},
            {"link": "https://www.facebook.com/topixconsortium/", "name": "facebook"}
        ])

        cls.user.profile.save()

        # Create Party
        cls.party = Party(cls.user)
        cls.party.get()
def login():
    if current_user.is_authenticated:
        return redirect(url_for('hcs'))

    form = LoginForm()
    if form.validate_on_submit():
        os.environ['SESSION_ID'] = form.sessionID.data

        try:

            user = User(user_id=form.sessionID.data)

            # checks if user is already in database
            if User.query.filter_by(
                    user_id=form.sessionID.data).first() != None:
                login_user(user)
                flash(f'Hi, you have been logged in.', 'success')

                return redirect(url_for('hcs'))

            # if not, add user to db and call forum fetcher
            else:
                db.session.add(user)

                # fetch Hcs
                HcFetch = HcFetcher(form.sessionID.data)
                HcFetch.get_grades()

                # fetch Los
                LoFetch = LoFetcher(form.sessionID.data)
                LoFetch.get_grades()

                db.session.commit()
                login_user(user)

                flash(f'Hi, you have been logged in.', 'success')
                return redirect(url_for('hcs'))
        except:
            flash('Login unsuccessful. Please check Session ID.', 'danger')
            db.session.rollback()

    return render_template('login.html', title='Welcome', form=form)
示例#17
0
 def post(self, request):
     basic_auth = request.META.get(
         'HTTP_AUTHORIZATION', ''
     )
     if re.match('Basic [A-Za-z0-9]', basic_auth):
         auth = basic_auth.partition(' ')[2]
         username, _, password = b64decode(auth).decode().partition(':')
         print(username, password)
         user = User(username=username, password=password)
         if valid_user(user):
             print('User validated!')
             parser = LandingPageParser(user)
             print('Parsing student...')
             student = parser.parse().__dict__
             print('Finished parsing student!')
             student.pop('_state')
             return JsonResponse(student)
         else:
             return JsonResponse({}, status=400)
     else:
         return JsonResponse({}, status=400)
示例#18
0
def create_test_user():
    password = '******'

    user_data = {
        'email':
        '*****@*****.**',
        'first_name':
        'aaa_unit_test',
        'last_name':
        'aaa_test_unit',
        'picture':
        'images/profile/default_user_icon.png',
        'password':
        password,
        'gender':
        'Female',
        'birthdate':
        '1980-01-12',
        'city':
        'Torreon',
        'occupation':
        'tester',
        'twitter_username':
        '',
        'place':
        '{"city":"Torreon","state":"Coah.","country_short":"MX","country":"Messico","lat":25.5428443,"long":-103.40678609999998}',
    }

    user = User.create(**user_data)
    Profile.create(user=user, **user_data)
    user = User.objects.filter(email=user_data['email'])[0]
    user.is_active = True

    # Extra fields
    # cls.user.profile.types_of_innovation = 'Product innovation,Technological innovation,Business model innovation'
    user.profile.organization = 'aaa_unit_test_organization'
    user.profile.statement = 'Hi im a test user generated from unit test suite'

    ## SOP
    user.profile.source_of_inspiration.add(SourceOfInspiration.create('Apple'))
    user.profile.source_of_inspiration.add(
        SourceOfInspiration.create('Microsoft'))
    user.profile.source_of_inspiration.add(
        SourceOfInspiration.create('Samsung'))
    ## Tags
    user.profile.tags.add(Tag.create('Innovation'))
    user.profile.tags.add(Tag.create('Social'))
    user.profile.tags.add(Tag.create('Design'))

    user.profile.sector = 'ICT'

    user.profile.technical_expertise = 'Digital fabrication - Digitalization of analog and traditional technologies'
    user.profile.size = 'A small enterprise (<50 staff)'

    user.profile.socialLinks = json.dumps([{
        "link": "top_ix",
        "name": "twitter"
    }, {
        "link": "www.google.it",
        "name": "google-plus"
    }, {
        "link": "https://www.facebook.com/topixconsortium/",
        "name": "facebook"
    }])
    user.save()
    user.profile.save()
    return user
示例#19
0
def shibcallback(request):
    # Callback from Shib login. Get ALL the meta!
    appdata_signed = request.GET.get("appdata", None)
    if not appdata_signed:
        response = PrettyJsonResponse({
            "ok":
            False,
            "error": ("No signed app data returned from Shibboleth."
                      " Please use the authorise endpoint.")
        })
        response.status_code = 400
        return response

    signer = TimestampSigner()
    try:
        # Expire our signed tokens after five minutes for added security
        appdata = signer.unsign(appdata_signed, max_age=300)
    except signing.SignatureExpired:
        response = PrettyJsonResponse({
            "ok":
            False,
            "error": ("Login data has expired. Please attempt to log in "
                      "again. If the issues persist please contact the "
                      "UCL API Team to rectify this.")
        })
        response.status_code = 400
        return response
    except signing.BadSignature:
        response = PrettyJsonResponse({
            "ok":
            False,
            "error": ("Bad signature. Please attempt to log in again. "
                      "If the issues persist please contact the UCL API "
                      "Team to rectify this.")
        })
        response.status_code = 400
        return response

    client_id = appdata[:33]
    state = appdata[33:]

    # We can trust this value because it was extracted from the signed data
    # string sent via Shibboleth
    app = App.objects.get(client_id=client_id)

    # Sometimes UCL doesn't give us the expected headers.
    # If a critical header is missing we error out.
    # If non-critical headers are missing we simply put a placeholder string.
    try:
        # This is used to find the correct user
        eppn = request.META['HTTP_EPPN']
        # We don't really use cn but because it's unique in the DB we can't
        # really put a place holder value.
        cn = request.META['HTTP_CN']
        # (aka UPI), also unique in the DB
        employee_id = request.META['HTTP_EMPLOYEEID']
    except KeyError:
        response = PrettyJsonResponse({
            "ok":
            False,
            "error": ("UCL has sent incomplete headers. If the issues persist"
                      "please contact the UCL API Team to rectify this.")
        })
        response.status_code = 400
        return response

    # TODO: Ask UCL what on earth are they doing by missing out headers, and
    # remind them we need to to be informed of these types of changes.
    # TODO: log to sentry that fields were missing...
    department = request.META.get('HTTP_DEPARTMENT', '')
    given_name = request.META.get('HTTP_GIVENNAME', '')
    display_name = request.META.get('HTTP_DISPLAYNAME', '')
    groups = request.META.get('HTTP_UCLINTRANETGROUPS', '')

    # We check whether the user is a member of any UCL Intranet Groups.
    # This is a quick litmus test to determine whether they should be able to
    # use an OAuth application.
    # We deny access to alumni, which does not have this Shibboleth attribute.
    # Test accounts also do not have this attribute, but we can check the
    # department attribute for the Shibtests department.
    # This lets App Store reviewers log in to apps that use the UCL API.
    if not groups:
        if department == "Shibtests" or eppn == SHIB_TEST_USER:
            groups = "shibtests"
        else:
            response = HttpResponse(
                ("Error 403 - denied. <br>"
                 "Unfortunately, alumni are not permitted to use UCL Apps."))
            response.status_code = 403
            return response

    # If a user has never used the API before then we need to sign them up
    try:
        # TODO: Handle MultipleObjectsReturned exception.
        # email field isn't unique at database level (on our side).
        # Alternatively, switch to employee_id (which is unique).
        user = User.objects.get(email=eppn)
    except User.DoesNotExist:
        # create a new user
        user = User(email=eppn,
                    full_name=display_name,
                    given_name=given_name,
                    department=department,
                    cn=cn,
                    raw_intranet_groups=groups,
                    employee_id=employee_id)

        user.save()
    else:
        # User exists already, so update the values if new ones are non-empty.
        user = User.objects.get(email=eppn)
        user.employee_id = employee_id
        if display_name:
            user.full_name = display_name
        if given_name:
            user.given_name = given_name
        if department:
            user.department = department
        if groups:
            user.raw_intranet_groups = groups
        user.save()

    # Log the user into the system using their User ID
    request.session["user_id"] = user.id

    signer = TimestampSigner()
    response_data = {
        "client_id": app.client_id,
        "state": state,
        "user_upi": user.employee_id
    }

    response_data_str = json.dumps(response_data, cls=DjangoJSONEncoder)
    response_data_signed = signer.sign(response_data_str)

    s = Scopes()

    page_data = {
        "app_name": app.name,
        "creator": app.user.full_name,
        "client_id": app.client_id,
        "state": state,
        "scopes": s.scope_dict(app.scope.scope_number),
        "user": {
            "full_name": user.full_name,
            "cn": user.cn,
            "email": user.email,
            "department": user.department,
            "upi": user.employee_id
        },
        "signed_data": response_data_signed
    }

    initial_data = json.dumps(page_data, cls=DjangoJSONEncoder)
    return render(request, 'permissions.html', {'initial_data': initial_data})
示例#20
0
def myapps_shibboleth_callback(request):
    # should auth user login or signup
    # then redirect to my apps homepage

    # Sometimes UCL doesn't give us the expected headers.
    # If a critical header is missing we error out.
    # If non-critical headers are missing we simply put a placeholder string.
    try:
        # This is used to find the correct user
        eppn = request.META['HTTP_EPPN']
        # We don't really use cn but because it's unique in the DB we can't
        # really put a place holder value.
        cn = request.META['HTTP_CN']
        # (aka UPI), also unique in the DB
        employee_id = request.META['HTTP_EMPLOYEEID']
    except KeyError:
        response = PrettyJsonResponse({
            "ok":
            False,
            "error": ("UCL has sent incomplete headers. If the issues persist"
                      "please contact the UCL API Team to rectify this.")
        })
        response.status_code = 400
        return response

    # TODO: Ask UCL what on earth are they doing by missing out headers, and
    # remind them we need to to be informed of these types of changes.
    # TODO: log to sentry that fields were missing...
    department = request.META.get('HTTP_DEPARTMENT', '')
    given_name = request.META.get('HTTP_GIVENNAME', '')
    display_name = request.META.get('HTTP_DISPLAYNAME', '')
    groups = request.META.get('HTTP_UCLINTRANETGROUPS', '')

    try:
        user = User.objects.get(email=eppn)
        # TODO: Handle MultipleObjectsReturned exception.
        # email field isn't unique at database level (on our side).
        # Alternatively, switch to employee_id (which is unique).
    except User.DoesNotExist:
        # create a new user
        new_user = User(email=eppn,
                        full_name=display_name,
                        given_name=given_name,
                        department=department,
                        cn=cn,
                        raw_intranet_groups=groups,
                        employee_id=employee_id)

        new_user.save()

        request.session["user_id"] = new_user.id
    else:
        # User exists already, so update the values if new ones are non-empty.
        user = User.objects.get(email=eppn)
        user.employee_id = employee_id
        if display_name:
            user.full_name = display_name
        if given_name:
            user.given_name = given_name
        if department:
            user.department = department
        if groups:
            user.raw_intranet_groups = groups
        user.save()

    return redirect("/oauth/myapps")
示例#21
0
 def test_2_check_reset_token(self):
     user = User.create(**self.userdata)
     profile = Profile.create(user=user, **self.userdata)
     print profile.reset_token
     self.assertIsNot(profile.reset_token, None, Colorizer.Red('Error during profile creation'))
示例#22
0
 def test_1_create(self):
     user = User.create(**self.userdata)
     profile = Profile.create(user=user, **self.userdata)
     self.assertIsInstance(profile, Profile, Colorizer.Red('Error during profile creation'))
示例#23
0
def signup_page(name=None):
    form = RegistrationForm(request.form,
                            captcha={'ip_address': request.environ.get('HTTP_X_REAL_IP',
                                                                       request.remote_addr)})
    if name is None:
        abort(404)
    if current_user.is_authenticated:
        return redirect(url_for('home'))

    if request.method == 'POST':
        if name is None:
            abort(404)
        if form.validate_on_submit():
            query = User.query.filter_by(is_reseller=True, username=name).first_or_404()
            email = form.email.data
            restrict_email = email.split('@')
            if restrict_email[1] == 'gmail.com' or restrict_email[1] == 'yahoo.com':
                registered_email = User.query.filter_by(email=form.email.data).first()
                registered_user = User.query.filter_by(username=form.username.data).first()
                if registered_user is None and registered_email is None:
                    verification_code = email_key_generator()
                    msg = Message('SafeCore Identity Confirmation',
                                  recipients=[form.email.data]
                                  )
                    msg.html = render_template('email.html',
                                               email=form.email.data,
                                               confirmation=verification_code)
                    mail.send(msg)
                    query = User(
                        form.first_name.data,
                        form.last_name.data,
                        form.email.data,
                        form.username.data,
                        form.password.data,
                        query.username
                    )

                    email_expiration = datetime.now() + timedelta(days=1)
                    email_verify = Email(user=query,
                                         confirmation_key=verification_code,
                                         registration_date=datetime.now(),
                                         valid=True,
                                         expiration_date=email_expiration
                                         )
                    notify = Notifications(user_id=query.id, notification_type='signup', confirmed_date=datetime.now(),
                                           notification_ip=request.environ.get('HTTP_X_REAL_IP',
                                                                               request.remote_addr))

                    db.session.add(query, email_verify, notify)
                    db.session.commit()
                    flash('Please check your email for verification!', 'info')
                    return redirect(url_for('login'))
                else:
                    flash('Username or email already exists!', 'warning')
                    return redirect(url_for('reseller.signup_page'))
            else:
                flash('We only accept email in Google and Yahoo', 'warning')
                return redirect(url_for('reseller.signup_page'))
        else:
            flash('Something went wrong! Please check your form and try again', 'warning')
            return redirect(url_for('reseller.signup_page'))
    form = RegistrationForm(request.form,
                            captcha={'ip_address': request.environ.get('HTTP_X_REAL_IP',
                                                                       request.remote_addr)})
    query = User.query.filter_by(is_reseller=True, username=name).first_or_404()
    if query.account_status == 'banned' or query.account_status == 'deactivated':
        abort(404)
    else:
        return render_template('my_page_signup.html', query=User.query.filter_by(is_reseller=True, username=name).first_or_404(), form=form, page_title='Register under ' + query.username)
示例#24
0
def shibcallback(request):
    # Callback from Shib login. Get ALL the meta!
    appdata_signed = request.GET.get("appdata", None)
    if not appdata_signed:
        response = PrettyJsonResponse({
            "ok":
            False,
            "error": ("No signed app data returned from Shibboleth."
                      " Please use the authorise endpoint.")
        })
        response.status_code = 400
        return response

    signer = TimestampSigner()
    try:
        # Expire our signed tokens after five minutes for added security
        appdata = signer.unsign(appdata_signed, max_age=300)
    except signing.SignatureExpired:
        response = PrettyJsonResponse({
            "ok":
            False,
            "error": ("Login data has expired. Please attempt to log in "
                      "again. If the issues persist please contact the "
                      "UCL API Team to rectify this.")
        })
        response.status_code = 400
        return response
    except signing.BadSignature:
        response = PrettyJsonResponse({
            "ok":
            False,
            "error": ("Bad signature. Please attempt to log in again. "
                      "If the issues persist please contact the UCL API "
                      "Team to rectify this.")
        })
        response.status_code = 400
        return response

    client_id = appdata[:33]
    state = appdata[33:]

    # We can trust this value because it was extracted from the signed data
    # string sent via Shibboleth
    app = App.objects.get(client_id=client_id)

    eppn = request.META['HTTP_EPPN']
    groups = request.META['HTTP_UCLINTRANETGROUPS']
    cn = request.META['HTTP_CN']
    department = request.META['HTTP_DEPARTMENT']
    given_name = request.META['HTTP_GIVENNAME']
    display_name = request.META['HTTP_DISPLAYNAME']
    employee_id = request.META['HTTP_EMPLOYEEID']

    # If a user has never used the API before then we need to sign them up
    try:
        user = User.objects.get(email=eppn)
    except User.DoesNotExist:
        # create a new user
        user = User(email=eppn,
                    full_name=display_name,
                    given_name=given_name,
                    department=department,
                    cn=cn,
                    raw_intranet_groups=groups,
                    employee_id=employee_id)

        user.save()
        keen_add_event.delay("signup", {
            "id": user.id,
            "email": eppn,
            "name": display_name
        })
    else:
        # User exists already, so update the values
        user = User.objects.get(email=eppn)
        user.full_name = display_name
        user.given_name = given_name
        user.department = department
        user.raw_intranet_groups = groups
        user.employee_id = employee_id
        user.save()

        keen_add_event.delay("User data updated", {
            "id": user.id,
            "email": eppn,
            "name": display_name
        })

    # Log the user into the system using their User ID
    request.session["user_id"] = user.id

    signer = TimestampSigner()
    response_data = {
        "client_id": app.client_id,
        "state": state,
        "user_upi": user.employee_id
    }

    response_data_str = json.dumps(response_data, cls=DjangoJSONEncoder)
    response_data_signed = signer.sign(response_data_str)

    s = Scopes()

    page_data = {
        "app_name": app.name,
        "creator": app.user.full_name,
        "client_id": app.client_id,
        "state": state,
        "scopes": s.scope_dict(app.scope.scope_number),
        "user": {
            "full_name": user.full_name,
            "cn": user.cn,
            "email": user.email,
            "department": user.department,
            "upi": user.employee_id
        },
        "signed_data": response_data_signed
    }

    initial_data = json.dumps(page_data, cls=DjangoJSONEncoder)
    return render(request, 'permissions.html', {'initial_data': initial_data})