예제 #1
0
def _email_two_factor_auth(user):
    # send email to user that has details on
    # how to apply TOTP to login to pybossa
    if user and user.email_addr:
        msg = dict(subject='One time password generation details for Pybossa',
                   recipients=[user.email_addr])
        msg['body'] = render_template('/account/email/otp.md', user=user)
        otpauths[user.email_addr] = None
        otpauths[user.email_addr] = OtpAuth(
            base64.b32encode(os.urandom(10)).decode('utf-8'))
        otpsecret = otpauths[user.email_addr]
        if otpsecret is None:
            flash(gettext("Problem with generating one time password"),
                  'error')
        else:
            otpcode = otpsecret.totp(period=600)  # otp valid for 10 mins
            print '********** OTP code generated before sending email: %r' % otpcode
            msg['html'] = render_template('/account/email/otp.html',
                                          user=user,
                                          otpcode=otpcode)
            mail_queue.enqueue(send_mail, msg)
            flash(
                gettext(
                    "An email has been sent to you with one time password"),
                'success')
    else:
        flash(
            gettext("We don't have this email in our records. "
                    "You may have signed up with a different "
                    "email or used Twitter, Facebook, or "
                    "Google to sign-in"), 'error')
예제 #2
0
def register():

	if request.method == 'POST':
		print 'Username: '******'Username']
		print 'Password: '******'Password']

		# Connect to database
		db = sqlite3.connect('google_authenticator.db')
		cursor = db.cursor()

		# Create secret and add user to database
		secret = base64.b32encode(os.urandom(10)).decode('utf-8')
		query = 'INSERT INTO USERS (USER, PASSWORD, GOOGLEAUTH) VALUES (\"' + request.form['Username'] + '\",\"' + request.form['Password'] + '\",\"' + secret + '\");'
		cursor.execute(query)
		db.commit()
		db.close()

		# Create unique QR code given secret, label, and issuer
		auth = OtpAuth(secret)
		secret_uri = auth.to_uri('totp', GALabel, GAIssuer)
		qr = QRCode()
		qr.add_data(secret_uri)
		qr.make()
		img = qr.make_image()
		#img.show()	# Opens tmp QR code image
		print 'Secret: ', secret
		print 'Secret Uri: ', secret_uri

		# Display QR code in web browser
		return redirect(getQRCodeGoogleUrl(secret_uri))

	return "Nothing to see here."
예제 #3
0
파일: oj.py 프로젝트: Gumbeat/Olymp
    def post(self, request):
        """
        User login api
        """
        data = request.data
        user = auth.authenticate(username=data["username"],
                                 password=data["password"])
        # None is returned if username or password is wrong
        if user:
            if user.is_disabled:
                return self.error("Ваш аккаунт был отключен.")
            if not user.two_factor_auth:
                auth.login(request, user)
                return self.success("Успешно")

            # `tfa_code` not in post data
            if user.two_factor_auth and "tfa_code" not in data:
                return self.error("2фа необходима")

            if OtpAuth(user.tfa_token).valid_totp(data["tfa_code"]):
                auth.login(request, user)
                return self.success("Успешно")
            else:
                return self.error("Неверный код 2фа")
        else:
            return self.error("Неверное имя пользователя или пароль")
예제 #4
0
파일: authy.py 프로젝트: jomarmar/dotfiles
def get_code(secret):
    secret = base64.b32decode(b32pad(secret.upper()))
    auth = OtpAuth(secret)  # a secret string
    code = auth.totp()  # generate a time based code
    code = str(code).zfill(6)

    return code
예제 #5
0
    def post(self, request):
        """
        用户登录API
        """
        data = request.data
        user = auth.authenticate(username=data["username"],
                                 password=data["password"])
        # 如果用户名或者密码错误就什么都没有返回
        if user:
            if user.is_disabled:
                return self.error("Your account has been disabled")
            # 如果不需要双因素验证,直接就返回得了,否则向下执行
            if not user.two_factor_auth:
                auth.login(request, user)
                return self.success("Succeeded")

            # 来到这里自然说明要双因素验证
            # 如果双因素验证码不在tfa_code请求数据里面,就返回错误
            if user.two_factor_auth and "tfa_code" not in data:
                return self.error("tfa_required")

            # 来到这里,说明需要双因素验证,而且双因素验证码也满足,这里就是判断两码是否一致
            # 成功就返回secceeded,错误就返回无效的双因素验证码提示信息
            # 传过来的tfa_code不是和数据库保存的数据一致,需要使用OtpAuth的valid_totp再加工一下还原
            if OtpAuth(user.tfa_token).valid_totp(data["tfa_code"]):
                auth.login(request, user)
                return self.success("Succeeded")
            else:
                return self.error("Invalid two factor verification code")
        else:
            # 最终如果是用户名或者密码出错就返回响应的信息
            return self.error("Invalid username or password")
예제 #6
0
    def post(self, request):
        """
        User login api
        """
        data = request.data
        user = auth.authenticate(username=data["username"],
                                 password=data["password"])
        # None is returned if username or password is wrong
        if user:
            if user.is_disabled:
                return self.error("Your account has been disabled")
            if not user.two_factor_auth:
                auth.login(request, user)
                return self.success("Succeeded")

            # `tfa_code` not in post data
            if user.two_factor_auth and "tfa_code" not in data:
                return self.error("tfa_required")

            if OtpAuth(user.tfa_token).valid_totp(data["tfa_code"]):
                auth.login(request, user)
                return self.success("Succeeded")
            else:
                return self.error("Invalid two factor verification code")
        else:
            if '@' in data["username"]:
                return self.error("Don't use email, use your username")
            return self.error("Invalid username or password")
예제 #7
0
def googleScan(inputStr):
    from otpauth import OtpAuth
    auth = OtpAuth(inputStr)  # a secret string
    # to_google(self, type, label, issuer, counter=None)
    s = auth.to_google(type='totp', issuer="PyPI", label='SHA1', counter='6')
    print(s)
    return s
def controle_otp():
    auth = OtpAuth(db_auth)
    print(auth)
    controle = auth.valid_totp(int(input('Voer code in')))
    if controle == True:
        print('Code geaccepteerd')
    else:
        print('Helaas de code is onjuist')
예제 #9
0
def create_tsa(username, user_hash):
    print str(user_hash)
    auth = OtpAuth(str(user_hash))  # a secret string
    s = auth.to_uri('totp', 'User:'******'Kuorra')
    img = qrcode.make(s)
    f = open("static/qr/output.png", "wb")
    img.save(f)
    f.close()
예제 #10
0
def test_totp():
    auth = OtpAuth('python')
    code = auth.totp()
    assert auth.valid_totp(code)

    # false
    assert auth.valid_totp(1234567) is False
    assert auth.valid_totp(123456) is False
예제 #11
0
파일: tests.py 프로젝트: xchf/ICQBPMSSOJ
 def _get_tfa_code(self):
     # 获得验证码
     # 先查找数据库对应的用户,生成一个二维码
     user = User.objects.first()
     code = OtpAuth(user.tfa_token).totp()
     if len(str(code)) < 6:
         code = (6 - len(str(code))) * "0" + str(code)
     return code
예제 #12
0
파일: tests.py 프로젝트: xchf/ICQBPMSSOJ
 def _get_tfa_code(self):
     # 获取双因素代码
     # 正向查询:一对多,查找第一条
     user = User.objects.first()
     code = OtpAuth(user.tfa_token).totp()
     if len(str(code)) < 6:
         code = (6 - len(str(code))) * "0" + str(code)
     return code
예제 #13
0
def test_hotp():
    auth = OtpAuth('python')
    code = auth.hotp(4)
    assert auth.valid_hotp(code) == 4

    # false
    assert auth.valid_hotp(1234567) is False
    assert auth.valid_hotp(123456) is False
    assert auth.valid_hotp('123456') is False
def controle_otp(response, pincode):
    auth = OtpAuth(response)
    controle = auth.valid_totp(int(pincode))
    if controle == True:
        print('Code geaccepteerd')
        return True
    else:
        print('Helaas de code is onjuist')
        return False
def nieuwe_gebruiker():
    global db_auth
    Random = str(
        (''.join(random.choice('ABDJFHE34543234') for _ in range(16))))
    db_auth = Random
    print(Random)
    auth = OtpAuth(Random)  # Moet 16 lang zijn
    s = auth.to_uri('totp', 'Jelle Huisman', 'NS Fietsenstalling')
    import qrcode
    img = qrcode.make(s)
    img.show()
예제 #16
0
 def put(self, request):
     code = request.data["code"]
     user = request.user
     if not user.two_factor_auth:
         return self.error("2FA is already turned off")
     if OtpAuth(user.tfa_token).valid_totp(code):
         user.two_factor_auth = False
         user.save()
         return self.success("Succeeded")
     else:
         return self.error("Invalid code")
예제 #17
0
파일: oj.py 프로젝트: Gumbeat/Olymp
 def put(self, request):
     code = request.data["code"]
     user = request.user
     if not user.two_factor_auth:
         return self.error("2ФА уже выключена")
     if OtpAuth(user.tfa_token).valid_totp(code):
         user.two_factor_auth = False
         user.save()
         return self.success("Успешно")
     else:
         return self.error("Неверный код")
예제 #18
0
def qrCoderValid(inputStr):
    auth = OtpAuth(inputStr)
    hotp_code = auth.hotp(6)
    valid = auth.valid_hotp(hotp_code)
    # hotp_code = auth.hotp(6)
    # valid = auth.valid_hotp(hotp_code)
    totp_code = auth.totp(period=30, )
    print(totp_code)
    if auth.valid_totp(totp_code):
        return totp_code
    return totp_code
예제 #19
0
 def put(self, user_id):
     """
     This is the endpoint that creates the user 2fa
     ---
     tags:
       - users 2fa
     parameters:
       - in: body
         name: body
         schema:
           id: 2fa_in
           properties:
             twoFACode:
               type: string
               description: code for 2fa
             twoFASecret:
               type: integer
               description: secret key for user
     responses:
       201:
         description: user 2fa secret
         schema:
           id: success
           properties:
             success:
               type: boolean
               value: true
       400:
         description: invalid 2fa secret or code
         schema:
           id: error
       404:
         description: invalid user
         schema:
           id: error
     """
     if user_id is None:
         return jsonify(error="invalid user id"), 404
     user = User.query.filter_by(id=user_id).first()
     if user is None:
         return jsonify(error="invalid user"), 404
     user2fa_secret = request.json.get('twoFASecret', None)
     if not user2fa_secret:
         return jsonify(error="invalid 2fa secret"), 400
     user2fa_code = request.json.get('twoFACode', None)
     if user2fa_code is None:
         return jsonify(error="invalid 2fa code"), 400
     auth = OtpAuth(user2fa_secret)
     if auth.valid_totp(user2fa_code):
         user.secure_id = user2fa_secret
         db.session.commit()
         return jsonify(success=True), 201
     return jsonify(error="wrong code"), 400
예제 #20
0
 def post(self, request):
     """
     Open 2FA
     """
     code = request.data["code"]
     user = request.user
     if OtpAuth(user.tfa_token).valid_totp(code):
         user.two_factor_auth = True
         user.save()
         return self.success("Succeeded")
     else:
         return self.error("Invalid code")
예제 #21
0
    def test_tfa_login(self):
        token = self._set_tfa()
        code = OtpAuth(token).totp()
        if len(str(code)) < 6:
            code = (6 - len(str(code))) * "0" + str(code)
        response = self.client.post(self.login_url,
                                    data={"username": self.username,
                                          "password": self.password,
                                          "tfa_code": code})
        self.assertDictEqual(response.data, {"error": None, "data": "Succeeded"})

        user = auth.get_user(self.client)
        self.assertTrue(user.is_authenticated)
예제 #22
0
 def post(self, request):
     """
     开启 2FA 模式
     """
     code = request.data["code"]
     user = request.user
     # 从数据库查找出对应的code和传过来的code比较,成功就设置双因素验证为True
     if OtpAuth(user.tfa_token).valid_totp(code):
         user.two_factor_auth = True
         user.save()
         return self.success("Succeeded")
     else:
         return self.error("Invalid code")
예제 #23
0
파일: oj.py 프로젝트: r14152/OnlineJudge
    def get(self, request):
        """
        Get QR code
        """
        user = request.user
        if user.two_factor_auth:
            return self.error("2FA is already turned on")
        token = rand_str()
        user.tfa_token = token
        user.save()

        label = f"{SysOptions.website_name_shortcut}:{user.username}"
        image = qrcode.make(OtpAuth(token).to_uri("totp", label, SysOptions.website_name))
        return self.success(img2base64(image))
def nieuwe_gebruiker():
    global db_auth
    Random = str(
        (''.join(random.choice('ABDJFHE34543234') for _ in range(16))))
    db_auth = Random
    print('test' + db_auth)
    auth = OtpAuth(Random)
    s = auth.to_uri('totp', 'NS', 'NS Fietsenstalling')
    qr = QRCode(version=1, error_correction=ERROR_CORRECT_L)
    qr.add_data(s)
    qr.make()
    img = qr.make_image()
    img.save("qrcode.png")
    return db_auth
 def create_qr(self):
     id = str(self.id)
     auth = OtpAuth(app.config['SECRET_KEY'] + id)  # a secret string
     email = self.email
     s = auth.to_uri('totp', email, 'Unit963')
     qr = qrcode.QRCode(
         version=1,
         error_correction=qrcode.constants.ERROR_CORRECT_L,
         box_size=15,
         border=5,
     )
     qr.add_data(s)
     img = qr.make_image(fill_color="#05528a", back_color="white")
     img.save('./MFA/static/QR/' + id + '.png')
예제 #26
0
    def POST_TSA(username, **k):
        message = None  # Error message
        form = config.web.input()  # get form data
        result = config.model.get_users(username)  # search for username data
        user_hash = str(result.user_hash)

        auth = OtpAuth(user_hash)
        if auth.valid_totp(form.authenticator):
            app.session.loggedin = True
            raise config.web.seeother('/')
        else:
            message = "Two Step Authenticator not valid"  # Error message
            result = config.model.get_users(
                username)  # search for username data
            result.username = config.make_secure_val(str(
                result.username))  # apply HMAC for username
            return config.render.tsa(result, message)  # render tsa.html
예제 #27
0
파일: oj.py 프로젝트: r14152/OnlineJudge
 def post(self, request):
     data = request.data
     user = auth.authenticate(username=request.user.username, password=data["password"])
     if user:
         if user.two_factor_auth:
             if "tfa_code" not in data:
                 return self.error("tfa_required")
             if not OtpAuth(user.tfa_token).valid_totp(data["tfa_code"]):
                 return self.error("Invalid two factor verification code")
         data["new_email"] = data["new_email"].lower()
         if User.objects.filter(email=data["new_email"]).exists():
             return self.error("The email is owned by other account")
         user.email = data["new_email"]
         user.save()
         return self.success("Succeeded")
     else:
         return self.error("Wrong password")
예제 #28
0
파일: tests.py 프로젝트: xchf/ICQBPMSSOJ
    def test_tfa_login(self):
        # 测试使用双因素验证登录,调用_set_tfa()生成双因素验证码
        token = self._set_tfa()
        # 使用一次性验证工具加工一下
        code = OtpAuth(token).totp()
        # code字符串化之后的长度若小于6,不足的长度就用0补齐,最后再次拼接字符串化的code,就保证验证码大于6位数
        if len(str(code)) < 6:
            code = (6 - len(str(code))) * "0" + str(code)
        # 直接请求,因为双因素验证码已经保存到数据库里面了
        response = self.client.post(self.login_url,
                                    data={"username": self.username,
                                          "password": self.password,
                                          "tfa_code": code})
        self.assertDictEqual(response.data, {"error": None, "data": "Succeeded"})

        user = auth.get_user(self.client)
        self.assertTrue(user.is_authenticated())
    def segundo_fator(self, metodo, chave):
        """
        Calcula e retorna one-time passwords para uso como segundo fator de
        autenticação baseados em tempo ou hashes criptografados.

        ARGS:
        - metodo (string): pode ser 'time' ou 'hmac'.
        - chave (string): a chave privada usada para gerar os códigos.

        """
        au = OtpAuth(chave)

        if metodo == 'time':
            return au.totp()
        elif metodo == 'hmac':
            return au.hotp()
        else:
            raise ValueError('método não identificado')
예제 #30
0
파일: oj.py 프로젝트: r14152/OnlineJudge
 def post(self, request):
     """
     User change password api
     """
     data = request.data
     username = request.user.username
     user = auth.authenticate(username=username, password=data["old_password"])
     if user:
         if user.two_factor_auth:
             if "tfa_code" not in data:
                 return self.error("tfa_required")
             if not OtpAuth(user.tfa_token).valid_totp(data["tfa_code"]):
                 return self.error("Invalid two factor verification code")
         user.set_password(data["new_password"])
         user.save()
         return self.success("Succeeded")
     else:
         return self.error("Invalid old password")