示例#1
0
def activate(request, activation_key,
             template_name='userena/activate_fail.html',
             extra_context=None):
   """
   Activate a user with an activation key.
   """
   user = UserenaSignup.objects.activate_user(activation_key)
   if user:
      # Sign the user in.
      auth_user = authenticate(identification=user.username,
                               check_password=False)
      UserDetail.set_activation_datetime(auth_user)
      login(request, auth_user)
      if userena_settings.USERENA_USE_MESSAGES:
          messages.success(request, _('Congratulations -- your Art of Gratitude account is confirmed!'),
                           fail_silently=True)
      if request.method == 'POST':
         form = ProfileForm(request.POST, user=user)
         if form.is_valid():
            form.save()
      redirect_to = settings.LOGIN_REDIRECT_URL % {'username': user.username }
      return redirect(redirect_to)
   else:
      if not extra_context: extra_context = {}
      return ExtraContextTemplateView.as_view(template_name=template_name,
                                            extra_context=extra_context)(request)
示例#2
0
   def create_profile_and_userdetail(self, user):
      userDetail = UserDetail()
      userDetail.user = user
      userDetail.save()
      userena_profile = UserenaSignup.objects.create_userena_profile(user)

      # All users have an empty profile
      profile_model = get_profile_model()
      try:
         new_profile = user.get_profile()
      except profile_model.DoesNotExist:
         new_profile = profile_model(user=user)
         new_profile.save(using=self._db)

      # Give permissions to view and change profile
      for perm in ASSIGNED_PERMISSIONS['profile']:
         assign(perm[0], user, new_profile)

      # Give permissions to view and change itself
      for perm in ASSIGNED_PERMISSIONS['user']:
         assign(perm[0], user, user)

      if settings.USERENA_ACTIVATION_REQUIRED:
         userena_profile.send_activation_email()

      return user
示例#3
0
def save_user_details(user, form):
   user_details_list = UserDetail.objects.filter(user = user.id)
   if (len(user_details_list) > 0):
      user_details = user_details_list[0]
   else:
      user_details = UserDetail()
   user_details.no_messages = form.cleaned_data['no_messages']
   user_details.save()
   return
示例#4
0
    def post(self):
        name = self.request.get('username')
        password = self.request.get('password')
        verify = self.request.get('verify')
        email = self.request.get('email')
        Name_Error = ''
        Password_Error = ''
        Name_color = 'has-success'
        Password_color = 'has-success'
        if name and password and password == verify:
            val = check_if_user_exist(name, password)
            if val == 1:
                salt = make_salt()
                self.response.headers.add_header(
                    'Set-Cookie', 'user-id={}; Path=/'.format(
                        make_pw_hash(name, password, salt)))
                password_hash = make_pw_hash(name, password, salt)
                user = UserDetail(name=name,
                                  password=password_hash,
                                  email=email)
                key = user.put()
                memcache.set('LOGGED_IN',
                             [name, '/logout', password_hash, key])

                referer = self.get_cookie('referer')
                if referer:
                    self.set_cookie('referer', '')
                    self.redirect(str(referer))
                    return
                self.redirect("/blog")
            else:
                Name_Error = 'User already exist'
                Name_color = 'has-error'
                Password_color = 'has-error'
        else:
            if not name:
                Name_Error = 'Please enter name'
                Name_color = 'has-error'
            if password and not password == verify:
                Password_Error = 'Your password do not match'
                Password_color = 'has-error'
            if not password:
                Password_Error = "Enter valid password"
                Password_color = 'has-error'
        self.render('form.html',
                    name=name,
                    email=email,
                    Name_Error=Name_Error,
                    Password_Error=Password_Error,
                    Name_color=Name_color,
                    Password_color=Password_color)
示例#5
0
def add_detail():
    if current_user.get_role() == '1':
        form = DetailForm()
        if form.validate_on_submit():
            _detail = UserDetail(form.name.data, form.street.data,
                                 form.city.data, form.phone.data,
                                 form.website.data, date.today(),
                                 current_user.get_id())
            _detail.date = datetime.now()
            db.session.add(_detail)
            db.session.commit()
            flash(u'Your details were submitted succsessfully.')
            return redirect(url_for('index'))
        return render_template('add_detail.html', form=form)
    return redirect(url_for('index'))
示例#6
0
    def post(self):

        t = check_if_logged_in(self.get_user_id())
        print t
        if not t[0]:
            self.redirect('/login')
            return

        subject = self.request.get('subject')
        content = self.request.get('content')

        if subject and content:
            user = UserDetail.query(
                UserDetail.password == memcache.get('LOGGED_IN')[2]).fetch()[0]
            k = Post(subject=subject, content=content, user=user.key).put()
            user.posts.append(k)
            user.put()
            #time.sleep(0.5)
            get_front(True)
            self.redirect("/blog/%d" % k.id())

        else:
            self.render('new post form.html',
                        subject=subject,
                        content=content,
                        error="Both fields are needed",
                        logged=True,
                        acount_name=t[3])
示例#7
0
def check_if_user_exist(name, password):
    users = UserDetail.query().fetch()
    for user in users:
        if user.name == name:
            h = user.password
            if check_password(name, password, h):
                return user
    return 1
示例#8
0
 def post(self):
     data=request.get_json()
     user=UserDetail(user_email=data['user_email'],user_name=data['user_name'])
     print(user)
     db_session.add(user)
     db_session.commit()
     print(user)
     return {'Message':'Success'}
示例#9
0
    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():
            user = form.save(commit=False)

            # cleaned (normalized) data
            name = form.cleaned_data['name']
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            email = form.cleaned_data['email']
            user_role = form.cleaned_data['user_role']

            # Login credentials in the default User table
            user.first_name = name
            user.set_password(password)
            user.save()

            # Other user details
            userDetail = UserDetail()
            userDetail.user_name = username
            userDetail.user_role = user_role
            userDetail.email = email
            userDetail.name = name
            userDetail.save()

            return redirect('user:login')

        return render(request, self.template_name, {'form': form})
示例#10
0
def add_detail():
    if current_user.get_role() == "1":
        form = DetailForm()
        if form.validate_on_submit():
            _detail = UserDetail(
                form.name.data,
                form.street.data,
                form.city.data,
                form.phone.data,
                form.website.data,
                date.today(),
                current_user.get_id(),
            )
            _detail.date = datetime.now()
            db.session.add(_detail)
            db.session.commit()
            flash(u"Your details were submitted succsessfully.")
            return redirect(url_for("index"))
        return render_template("add_detail.html", form=form)
    return redirect(url_for("index"))
示例#11
0
   def fix_profile_and_userdetail(self, user):
      userDetail = UserDetail()
      userDetail.user = user
      userDetail.save()

      # All users have an empty profile
      profile_model = get_profile_model()
      try:
         new_profile = user.get_profile()
      except profile_model.DoesNotExist:
         new_profile = profile_model(user=user)
         new_profile.save(using=self._db)

      # Give permissions to view and change profile
      for perm in ASSIGNED_PERMISSIONS['profile']:
         assign(perm[0], user, new_profile)

      # Give permissions to view and change itself
      for perm in ASSIGNED_PERMISSIONS['user']:
         assign(perm[0], user, user)

      return user
示例#12
0
def register_user_details():
    """ Registers a new user details to Xena's UserDetail model.

    :return : Render the common post platform template.
    """

    if request.method == 'POST':
        data = request.form  # access form data from request.
        user_detail = UserDetail(
            user_detail_id=data['user_id'],
            age=data['age'],
            first_name=data['firstname'],
            last_name=data['lastname'],
            address=data['address'],
            contact_num=data['contact_num']
        )
        user_detail.create()  # add details for the specified user.

        return redirect(
            url_for(
                'get_common_posts'
            )
        )
示例#13
0
def get_user_details(user):
   user_details_list = UserDetail.objects.filter(user = user.id)
   if len(user_details_list) == 0:
      user_details = UserDetail()
      user_details.user = user
      user_details.smartphone = True
      user_details.no_messages = False
      user_details.save()
      return user_details
   else:
      return user_details_list[0]
示例#14
0
def save_memberships_from_form(user, form):
   delete_memberships_for_user(user)
   for project in form.cleaned_data['surveys']:
      membership = Membership(user = user, project = project)
      membership.save()
   user_details_list = UserDetail.objects.filter(user = user.id)
   if (len(user_details_list) > 0):
      user_details = user_details_list[0]
   else:
      user_details = UserDetail()
   user_details.phone_number = form.cleaned_data['phone_number']
   user_details.smartphone = form.cleaned_data['smartphone']
   user_details.no_messages = form.cleaned_data['no_messages']
   user_details.save()
   return
示例#15
0
def signup():
    try:
        data = request.get_json()
        if all(keys in data for keys in SIGNUP_LST):
            if data['email'].endswith('@fleetstudio.com'):
                sess = Session()
                user_exists = sess.query(UserDetail).filter_by(
                    email=data['email'].lower()).first()
                if not user_exists:
                    sess = Session()
                    new_user = UserDetail(name=data['username'].upper(), passwd=data['password'], \
                                        email=data['email'].lower(), phone=data['phone'])
                    sess.add(new_user)
                    sess.commit()
                    user_name = new_user.name
                    sess.close()
                    return jsonify({
                        "status":
                        201,
                        "result":
                        f"User {user_name} has been created successfully."
                    })
                else:
                    sess.close()
                    return jsonify({
                        "status":
                        200,
                        "result":
                        f"User {user_exists.name} Already Exists. Please Login...."
                    })
            else:
                return jsonify({
                    "status": 200,
                    "result": "Enter a Valid Email-ID"
                })
        else:
            return jsonify({"status": 400, "result": "Error in JSON format"})
    except Exception as exception:
        return jsonify({"status": 500, "result": exception})
示例#16
0
 def getGratitudeDayNumber(self, user):
    today = datetime.datetime.now()
    activationDatetime = UserDetail.get_activation_datetime(user)
    delta = today - activationDatetime
    dayNumber = delta.days + 1
    return dayNumber
示例#17
0
def get_user(user_id):
    return UserDetail.query(UserDetail.password == user_id).fetch()
示例#18
0
def register(request):
    if request.method == 'POST':
        username = request.POST.get('username', '')
        email = request.POST.get('email', '')
        password = request.POST.get('password', '')
        cellphone = request.POST.get('cellphone', '')
        companyName = request.POST.get('companyName', '')
        servercnt = request.POST.get('servercnt', '')
        organization_name = companyName
        sub_domain_name = request.POST.get('sub_domain', '')
        if not User.objects.filter(username=username):
            user = User(username=username,
                        email=email,
                        is_superuser=False,
                        is_staff=True,
                        is_active=True,
                        date_joined=str(datetime.datetime.now()))
            user.set_password(password)
            user.save()
            user_details = UserDetail(email=email,
                                      phone=cellphone,
                                      company=companyName,
                                      password=password,
                                      server_count=servercnt,
                                      name=username,
                                      org_name=organization_name,
                                      domain_name=sub_domain_name,
                                      user=user)

            org = None
            sentryInstance = None
            instance_list = AliyunSDK.AliyunSDK.get_instances()
            instance_list = instance_list['Instances']['Instance']
            sentry_list = []
            for e in instance_list:
                if e['InstanceName'][:len(settings.ALIYUN_ECS_SENTRY_INSTANCE_PREFIX)] == settings.ALIYUN_ECS_SENTRY_INSTANCE_PREFIX:
                    sentry_list.append(e)
            print 'sentry instance count: ', len(sentry_list)
            sentry_count = len(sentry_list)
            sentry_index = random.randint(0, sentry_count-1)
            sentry_instance = sentry_list[sentry_index]
            # create organization
            org_list = Organization.objects.filter(sentry_instance=sentry_instance['InstanceName'])
            while len(org_list) >= settings.MAX_SENTRY_INSTANCE_COUNT:
                sentry_index = random.randint(0, sentry_count-1)
                sentry_instance = sentry_list[sentry_index]
                org_list = Organization.objects.filter(sentry_instance=sentry_instance['InstanceName'])

            # update sentry_instance model
            sentry_ipaddress = sentry_instance['PublicIpAddress']['IpAddress'][0]
            print 'ipaddress = ', sentry_ipaddress
            url_prefix = "http://%s:%s" % (sentry_ipaddress, settings.SENTRY_DEFALUT_PORT)
            se_inst = SentryInstance.objects.filter(sentry_instance_name=sentry_instance['InstanceName'])
            if not se_inst:
                print 'sentry_instance_name = ', sentry_instance['InstanceName']
                sentryInstance = SentryInstance.objects.create(sentry_instance_name=sentry_instance['InstanceName'],
                                                sentry_instance_url_prefix=url_prefix)

            domain_name = sub_domain_name + settings.DEFAULT_SUB_DOMAIN_SUFFIX
            if not (Organization.objects.filter(organization_name=organization_name)
                and Organization.objects.filter(sub_domain_name=domain_name)):
                org = Organization(organization_name=organization_name,
                                   domain_name=sub_domain_name + settings.DEFAULT_SUB_DOMAIN_SUFFIX,
                                   sentry_instance=sentry_instance['InstanceName'])
            else:
                return render_to_response("loginsight/500.html")

            # save to database
            user_details.save()
            org.save()
            # add nginx vhost conf
            VHost.addVhostConf(domain=domain_name, organization=organization_name, sentry_url=url_prefix)
            VHost.reload_nginx()

            # add domain record for Aliyun Wan network
            resp = AliyunSDK.AliyunSDK.add_domain_record(domain_name=settings.OFFICIAL_DOMAIN_NAME,
                                                         RR=domain_name,
                                                         Type="A",
                                                         Value=sentry_ipaddress)
            return render_to_response("loginsight/signup-com.html")

        else:
            return render_to_response('loginsight/signup-infor.html',  context_instance=RequestContext(request))
    c = {}
    c.update(csrf(request))
    return render_to_response("loginsight/signup-infor.html", c)
示例#19
0
文件: mock.py 项目: v1ckxy/MSN
 def _add_user(self, email):
     u = User(gen_uuid(), email, True, UserStatus(email))
     self._user_by_uuid[u.uuid] = u
     self._user_by_email[u.email] = u
     self._detail_by_uuid[u.uuid] = UserDetail({})