示例#1
0
文件: views.py 项目: jeezybrick/ad_f
    def post(self, request, *args, **kwargs):
        """
        Would help to validate user and login the user.
        """
        model = kwargs['model']

        form = self.form_class(request.POST)

        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            user = authenticate(model, email=email, password=password)

            if user is not None:
                login(request, user)
                request.session['_id'] = user.pk

                # if model is publisher model.
                if model == Publisher:
                    request.session['user_type'] = constants.USER_PUBLISHER
                    return HttpResponseRedirect(self.get_success_url())
                elif model == Sponsor:
                    # if model is sponsor model.
                    request.session['user_type'] = constants.USER_SPONSOR
                    return HttpResponseRedirect(self.get_success_url())
            messages.error(request, "Wrong username and Password combination.")
            return self.form_invalid(form)
        else:
            return self.form_invalid(form)
示例#2
0
    def runTest(self):
        #malformated, nonsensical uri
        bad_uri = "garbage"
        #Should return None
        self.assertEqual(login(bad_uri), None)

        valid_uri = ""
        #retrieve a uri
        with open('valid_image_URI', 'r') as myfile:
            valid_uri=myfile.read().replace('\n', '')
        self.assertEqual(login(valid_uri), "fgf")
示例#3
0
    def __init__(self, parent=None):
        super(CalculatorForm, self).__init__(parent)
        backend.login()
        d=backend.getAllContacts()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.rows=len(d)
        self.cols=4
        self.ui.tableWidget.setRowCount(self.rows)
        self.ui.tableWidget.setColumnCount(self.cols)
        self.ui.tableWidget.setHorizontalHeaderItem(0,QtGui.QTableWidgetItem("id"))
        self.ui.tableWidget.setHorizontalHeaderItem(1,QtGui.QTableWidgetItem(u"用户"))
        self.ui.tableWidget.setHorizontalHeaderItem(2,QtGui.QTableWidgetItem(u"合同号"))
		self.ui.tableWidget.setHorizontalHeaderItem(2,QtGui.QTableWidgetItem(u"发货时间"))
示例#4
0
文件: packs.py 项目: mahongquan/parts
 def showdata(self,contactid):
     if not backend.islogin:
         backend.login()
     d=backend.getAllPack()
     self.rows=len(d)
     self.cols=2
     self.ui.tableWidget.setRowCount(self.rows)
     self.ui.tableWidget.setColumnCount(self.cols)
     self.ui.tableWidget.setHorizontalHeaderItem(0,QtGui.QTableWidgetItem("id"))
     self.ui.tableWidget.setHorizontalHeaderItem(1,QtGui.QTableWidgetItem("名称"))
     for i in range(len(d)):
         one=d[i]
         self.ui.tableWidget.setItem(i, 0, QtGui.QTableWidgetItem(str(one["id"])))
         self.ui.tableWidget.setItem(i, 1, QtGui.QTableWidgetItem(one["name"]))
         i+=1
示例#5
0
def signin(request):
    if request.method == 'POST':
        signin_form = SignInForm(request.POST)
        if signin_form.is_valid():
            email = signin_form.cleaned_data.get('email')
            password = signin_form.cleaned_data.get('password')
            user = authenticate(request, email=email, password=password)
            if user:
                login(request, user)
        else:
            messages.error(request, 'Error')
        redirect_to = request.GET.get(settings.REDIRECT_FIELD_NAME,
                                      'academy_site:home')
        return redirect(redirect_to)
    else:
        raise Http404
示例#6
0
def start_login(uname, password):
    cookie = ""

    # login
    print("1")
    cookie_str, text = login(uname, password)
    cookie = merge_cookie(cookie, cookie_str)
    print("Cookie: ", cookie)
    print("Res text: ", text)

    # text to json object
    text_json = json.loads(text)
    if not text_json["status"]:
        raise LoginException("第一阶段登录错误")

    # login get more cookie
    print("2")
    url = text_json["url"].replace("https", "http")
    cookie_str, text = get_req_to_cookie(url, cookie_str)
    cookie = merge_cookie(cookie, cookie_str)
    print("Cookie: ", cookie)
    print("Res text: ", text)
    text = json.loads(text)
    name = text["msg"]["name"]

    # get oauth cookie
    print("3")
    cookie_str, text = get_oauth(cookie)
    cookie = merge_cookie(cookie, cookie_str)
    print("Cookie: ", cookie)
    # print("Res text: ", text)

    return cookie, name
示例#7
0
def login():
    if request.method == 'POST':
        # get form fields
        username = request.form['username']
        password = request.form['password']

        # connects to api and runs the login POST
        response = backend.login(username=username, password=password)
        userIPaddress = request.environ.get('HTTP_X_REAL_IP',
                                            request.remote_addr)
        #if it succeeds the login
        if 'Success' in response:
            print("{} logged in from {}".format(username, userIPaddress))
            session['logged_in'] = True
            session['username'] = response['Success']['username']
            session['name'] = response['Success']['name']
            flash("You are now logged in", 'success')
            return redirect(url_for('index'))
        #if it fails login
        elif 'Error' in response:
            error = response['Error']
            session['logged_in'] = False
            print("Login failed by \'{}\' with username \'{}\'".format(
                userIPaddress, username))
            return render_template('login.html', error=error)
    return render_template('login.html')
示例#8
0
def upload_file(bot, update):
    file_id = update.message.video.file_id
    text = update.message.caption
    filename = text.lower().replace(' ', '-') if text else 'hackathon-mipt'
    if file_id:
        try:
            pure_file = bot.get_file(file_id)
        except Exception as e:
            print(e)
            return False
        else:
            try:
                filepath = os.path.join(os.getcwd(), filename)
                pure_file.download(custom_path=filepath)
                try:
                    #hardcode
                    user_ = login(username, password)
                    user_.add_video(filename, filepath)
                    os.remove(filepath)
                    bot.send_message(
                        chat_id=update.message.chat_id,
                        text=text_messages.success_upload_msg.format(
                            update.message.from_user.first_name, filename))
                    return True
                except Exception as e:
                    print('Upload fail!')
                    print(e)
                    return False
            except ValueError as e:
                print(e)
                return False
    else:
        return False
示例#9
0
def main():
    '''
    for i in range(1,len(sys.argv)):
        print str(sys.argv[i])
    '''
    output = "output"
    got = sys.argv

    if (sys.argv[1] == 'register'):
        username = sys.argv[2]
        img = sys.argv[3]
        if backend.register(username, [img]):
            output = 'success'
        else:
            output = 'register failed'

    elif (sys.argv[1] == 'login'):
        imgs = sys.argv[2:]
        if len(imgs) != 3:
            print "error, 3 URIS required, got:", len(imgs)
            return
        username = backend.login(imgs, MEDIUM_SECURITY)
        if not username:
            output = "NONEFOUND "
        else:
            output = username
            print username
    else:
        output = "failed"

    with open('backend_out', 'a') as the_file:
        the_file.write(output + '\n')

    with open('debug', 'a') as the_file:
        the_file.write(str(got) + '\n')
示例#10
0
def log_user_in():
    jsonresponse = request.get_json()
    status = {'status': False, 'sessionid': ''}
    if (backend.login(jsonresponse)):
        status['sessionid'] = backend.create_keygen(jsonresponse)
        status['status'] = True
    return json.dumps(status)
示例#11
0
def main():
    user = login('liker', 'qwerty12345')
    #video = user.get_video('hackathon-mipt', '/home/aleksei/pizda')

    # user.add_video('blockchaining', '/home/aleksei/jordan.txt', 'Ooops, there is no any video')

    videos_list = User.get_videos_list('empty-test')
    print(videos_list)
示例#12
0
	def login(self):
		result = backend.login(str(self.userField.text()), str(self.passwordField.text()))
		if result['code'] != 1 or len(result['message']) == 0:
			common.showError('Login', 'login failed')
		else:
			common.showMsg('Login', 'login Successful')
			newWindow = MainMenu(self)
			self.hide()
			newWindow.show()
示例#13
0
文件: items.py 项目: mahongquan/parts
 def showdata(self):
     if not backend.islogin:
         backend.login()
     d=backend.getItem()
     self.rows=len(d)
     self.cols=4
     self.ui.tableWidget.setRowCount(self.rows)
     self.ui.tableWidget.setColumnCount(self.cols)
     self.ui.tableWidget.setHorizontalHeaderItem(0,QtGui.QTableWidgetItem("id"))
     self.ui.tableWidget.setHorizontalHeaderItem(1,QtGui.QTableWidgetItem("名称"))
     self.ui.tableWidget.setHorizontalHeaderItem(3,QtGui.QTableWidgetItem("规格"))
     self.ui.tableWidget.setHorizontalHeaderItem(2,QtGui.QTableWidgetItem("编号"))
     for i in range(len(d)):
         one=d[i]
         self.ui.tableWidget.setItem(i, 0, QtGui.QTableWidgetItem(str(one["id"])))
         self.ui.tableWidget.setItem(i, 1, QtGui.QTableWidgetItem(one["name"]))
         self.ui.tableWidget.setItem(i, 3, QtGui.QTableWidgetItem(one["guige"]))
         self.ui.tableWidget.setItem(i, 2, QtGui.QTableWidgetItem(one["bh"]))
示例#14
0
文件: views.py 项目: Safoniks/Academy
def login_view(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            user = authenticate(request, email=email, password=password)
            if user:
                login(request, user)
                redirect_to = request.GET.get(settings.REDIRECT_FIELD_NAME,
                                              user.get_default_page())
                return redirect(redirect_to)
            else:
                form = LoginForm()
    else:
        form = LoginForm()
    return render(request, 'academy_admin/login.html', {
        'login_form': form,
    })
示例#15
0
def signup(request):
    if request.method == 'POST':
        signup_form = SignUpForm(request.POST)
        if signup_form.is_valid():
            signup_form.save()
            email = signup_form.cleaned_data.get('email')
            password = signup_form.cleaned_data.get('password')
            user = authenticate(request, email=email, password=password)
            login(request, user)
            send_confirmation_email(user)
            messages.success(request, 'Підтвердження емейла на почті')
        else:
            messages.error(request, 'Error')
        print(signup_form.errors)
        redirect_to = request.GET.get(settings.REDIRECT_FIELD_NAME,
                                      'academy_site:home')
        return redirect(redirect_to)
    else:
        raise Http404
示例#16
0
 def Login():
     user = (Usernamelog.get())
     pas = (Passwordlog.get())
     for row in backend.login(Usernamelog.get(), Passwordlog.get()):
         if (user in row and pas in row):
             openReg()
         else:
             tkinter.messagebox.askyesno('Bank Management Login System',
                                         'Invalid Login')
             Usernamelog.set("")
             Passwordlog.set("")
示例#17
0
def signup_course(request, city_slug, theme_slug, course_slug):
    user = request.user
    try:
        course = Course.objects.get(theme__city__slug=city_slug,
                                    theme__slug=theme_slug,
                                    slug=course_slug,
                                    status=AVAILABLE)
    except ObjectDoesNotExist:
        raise Http404
    if course.is_sold_out or course.is_archived:
        raise Http404
    if request.method == 'POST':
        form = SignUpCourseForm(request.POST,
                                request.FILES,
                                user=user,
                                course=course)
        if form.is_valid():
            user_course = form.save()
            if user_course.user and user_course.user != user:
                login(request, user_course.user.auth_user)
            if not user_course.is_confirmed:
                send_confirmation_email(user_course)
            redirect_to = request.GET.get(settings.REDIRECT_FIELD_NAME,
                                          'academy_site:course_detail')
            return redirect(redirect_to,
                            city_slug=city_slug,
                            theme_slug=theme_slug,
                            course_slug=course_slug)
    else:
        form = SignUpCourseForm(user=user, course=course)
    context = {
        'user': user,
        'signup_form': SignUpForm(),
        'signin_form': SignInForm(),
        'course': course,
        'form': form,
        'reset_password_form': ResetPasswordForm(),
        **request.common_content,
    }
    return render(request, 'academy_site/signup_course.html', context)
示例#18
0
def api():
    # Qua uso il token per ottenere le credenziali associate al token creato 
    if request.method == 'GET':
        token = None #"azzero" il token in modo da non usare quello già salvato nella variabile
        # Se c'è il token nelle headers, lo salvo
        if 'x-access-token' in request.headers:
            token = request.headers['x-access-token']

        # Se non c'è il token
        if not token:
            return jsonify({'message': 'Token is missing!'}), 403

        try:
            # Provo a decodificare il token usando la secret key
            jwt.decode(token, app.config['SECRET_KEY'])
            creds = credentials.get(token)
            #return jsonify({'creds': creds})
        except:
            # Se non funziona, il token è incorretto
            return jsonify({'message': 'Incorrect token!'}), 403

        d = {}
        # Creo la sessione con username e password
        requestSession = b.login(creds['username'], creds['password'])
        query = str(request.args['query'])
        try:
            if query == 'marks':
                m = b.getFullMarks(requestSession)
                for i in range(len(subjectNames)):
                    d[subjectNames[i]] = m[i]
                return jsonify(d)
            elif query == 'names':
                m = b.getNames(requestSession)
                return jsonify(m)
            elif query == 'calendar':
                m = b.calendar(requestSession)
                d['Calendar'] = m
                return jsonify(d)
            elif query == 'badge':
                m = b.badge(requestSession)
                d['Badge'] = m
                return jsonify(d)
            elif query == 'userdetails':
                m = b.getUserDetails(requestSession)
                d['Name'] = m[0]
                d['Class'] = m[1]
                return jsonify(d)
        except:
            return jsonify({'message': 'invalid credentials'}), 500
示例#19
0
def do_admin_login():
    POST_IMAGE = str(request.form['imageUrl'])
    POST_URL = str(request.form['txtUrl'])
    POST_URL = POST_URL.split('/')[-1]

    IMAGES = POST_IMAGE.split("#*^/")
    print "In register. Images len: " + str(len(IMAGES))

    result = backend.login(IMAGES, MEDIUM_SECURITY)
    if result != None:
        print "CLASSIFIED SUCCESSFULLY", result
        session['logged_in'] = True
    else:
        print "CLASSIFICATION FAILED"
        return log_in(None)
    return log_in(result)
示例#20
0
def login():
    try:
        info = None
        if request.method == 'POST':
            ok, info = bc.login(request.form['email'],
                                request.form['password'])
            if ok:
                username = bc.getUserName(info)
                resp = make_response(redirect('/square'))
                resp.set_cookie('username', username, max_age=3600)
                resp.set_cookie('userID', info, max_age=3600)
                return resp
        return render_template("login.html", error=info)
    except KeyError:
        print(KeyError, " keyerror for username")
        return redirect('/')
示例#21
0
def get_user():
    """
    When the user clicks on the Log In button in the Log In Page this function takes the username and the password
    he/she typed and the os path of his/her chosen certificate. Calls the login() function in the backend.py script,
    in order to check if the typed username and password are correct and if the chosen certificate has been issued by
    the Password Manager Application. If these are correct then the user can access his/her account.
    If not, he/she has 9 tries more to log in with time delay, else the Application will close.
    Also,the user is being informed about the errors and the remaining tries to login.
    Finally, the user will be informed if his/her account is safe or his/her saved passwords has been unauthorized changed
    :return: None
    """

    global tries, delay
    uName = uNameEL.get()
    usPswd = pwdEL.get()
    try:
        cert_path = filename
        status = backend.login(uName, usPswd, cert_path)

        if status != 1 and tries > 0:
            answer = backend.connect(uName)
            if answer == 1:
                showwarning("WARNING",
                            "Non authorized password modification!!")
            elif answer == 0:
                showinfo("Password Integrity",
                         "Everything seems to be as you left!")
            enter_app()
        elif tries == 0:
            showwarning("Login", "Can't authenticate!\nClosing application!")
            rootA.destroy()

        else:
            tries -= 1
            showwarning(
                "Login", "Can't login! Tries left " + str(tries) +
                "\nDelaying your entry..")
            time.sleep(delay)
            delay += 5

    except NameError:
        showinfo("Login", "Load your certificate!")
示例#22
0
def subscribeWhisper():
    session['whisperfeed'] = True
    session['wf_changed'] = 'true'
    backend.makeFriend(request.form['username'], request.form['auth_token'], 'whisper_feed')
    origAT = request.form['auth_token']
    origUN = request.form['username']
    r = backend.login('whisper_feed', 'Banvanphan2105!')
    at = r['auth_token']
    backend.makeFriend('whisper_feed', at, origUN)

    f = open(APP_STATIC + 'img/whisper-welcome.png')
    r = backend.sendSnap(WF_USERNAME, at, backend.encrypt_image(f.read()), request.form['username'], 10)
    f.close()

    session['auth_token'] = origAT
    session['username'] = origUN
    if r == 200:
        return "success"
    else:
        return "false"
示例#23
0
def login():
    if request.method == 'POST':
        args = parseParameter(request.data.decode('utf-8'))
        user_id = args['user_id']
        password = args['password']
    else:
        user_id = request.args.get('user_id')
        password = request.args.get('password')

    res = {"state": False}
    user_name, user_type = B.login(user_id, password)
    if user_name:
        res["state"] = True
        resp = make_response(json.dumps(res))
        resp.set_cookie("user_name", user_name, max_age=LIFE_TIME)
        resp.set_cookie("user_id", user_id, max_age=LIFE_TIME)
        resp.set_cookie("user_type", user_type, max_age=LIFE_TIME)
    else:
        resp = make_response(json.dumps(res))
    return resp
示例#24
0
def message_callback_body(bot, update):
    text = update.message.text
    if text:
        #Hardcode
        text = text.lower()
        print(text)
        filepath = os.path.join(os.getcwd(), text)
        user_ = login(username, password)
        user_.get_video(text, filepath)
        while not os.path.isfile(filepath):
            sleep(1)
        bot.send_message(chat_id=update.message.chat_id,
                         text=text_messages.success_download_msg.format(
                             update.message.from_user.first_name, text))
        bot.send_video(chat_id=update.message.chat_id,
                       video=open(filepath, 'rb'))
        os.remove(filepath)
    else:
        bot.send_message(chat_id=update.message.chat_id,
                         text=text_messages.download_error_msg.format(
                             update.message.from_user.first_name))
示例#25
0
def login():
    error = None
    if request.method == 'POST':
        try: 
            log.info('Start reading database')
            # do risky stuff
            r = backend.login(request.form['username'], request.form['password'])
            if r != False:
                print r
                session['username'] = r['username']
                session['auth_token'] = r['auth_token']
                session['added_friends_timestamp'] = r['added_friends_timestamp']

                secretSanta = False
                whisperFeed = False
                for friend in r['friends']:
                    if friend['name'] == 'secret_snapta':
                        secretSanta = True
                    if friend['name'] == 'whisper_feed':
                        whisperFeed = True

                session['whisperfeed'] = whisperFeed
                session['wf_changed'] = 'false'
                session['snapta'] = secretSanta
                session['snapta_changed'] = 'false'

                return redirect(url_for('snapfeed'))
            else:
                error = 'Invalid username/password combination'
                return render_template('login.html', error=error)
        except:

            # http://docs.python.org/2/library/sys.html
            _, ex, _ = sys.exc_info()
            log.error(ex.message)
    else:
        return render_template('login.html')
示例#26
0
def main():
    '''entry point '''
    # my_wunder = MyWunder()

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--init',
        help='init local support, user -eEMail -pPassword to finish it',
        action='store_true')
    parser.add_argument('-e', '--email', help='your email address')
    parser.add_argument('-p', '--password', help='your password')
    parser.add_argument('-l',
                        '--lists',
                        help='show lists',
                        action='store_true')
    parser.add_argument('-t',
                        '--tasks',
                        help='show tasks',
                        action='store_true')
    parser.add_argument('-u',
                        '--update',
                        help='update database',
                        action='store_true')
    parser.add_argument('-n', '--name', help="list name")
    parser.add_argument('-m', '--month', help="query by month", type=int)
    parser.add_argument('-s',
                        '--sum',
                        help="sum the number at title",
                        action="store_true")

    args = parser.parse_args()

    if args.init:
        assert args.email, 'need user, use -h to see more.'
        assert args.password, 'need password, use -h to see more.'
        my_wunder.login(args.email, args.password)
        my_wunder.init_db()

    elif args.lists:
        if args.name:
            list_id = my_wunder.query_list(args.name)
            print list_id
        else:
            l = my_wunder.query_list()
            format_printer(l)
    elif args.tasks:
        assert args.name, "you must use -n LISTNAME to assign the list name for tasks"
        l = my_wunder.query_tasks(args.name)
        if args.month:
            month = args.month

            def month_filter(tk):
                d = dateutil.parser.parse(tk['created_at'])
                y, da, day = str(d).split('-')
                return int(da) == month and datetime.now().year == int(y)

            l = filter(month_filter, l)
        format_printer(l)
        if args.sum:
            number_filter_func = lambda d: list(
                set(re.findall('\d*', d)) - set(['']))
            item_number_result_list = [
                number_filter_func(d['title']) for d in l
                if len(number_filter_func(d['title'])) > 0
            ]
            totals = sum([
                sum([float(ii) for ii in i]) for i in item_number_result_list
            ])
            logging.info("totals %f", totals)
            print "totals %f" % totals
    elif args.update:
        start_sync()
    else:
        l = my_wunder.query_list()
        format_printer(l)