Simple Login - Login Extension for Flask - maintainer @cuducos

Overview

GitHub Actions PyPI PyPI versions PyPI formats Flask Documentation

Login Extension for Flask

The simplest way to add login to flask!

How it works

First, install it from PyPI:

$ pip install flask_simplelogin

Then, use it in your app:

from flask import Flask
from flask_simplelogin import SimpleLogin

app = Flask(__name__)
SimpleLogin(app)

That's it!

Now you have /login and /logout routes in your application.

The username defaults to admin and the password defaults to secret — yeah that's not clever, check the docs to see how to configure it properly!

Login Screen

Check the documentation for more details!

Comments
  • changed username field to not be autocapitalized

    changed username field to not be autocapitalized

    the current auto captilized field might be annoying when accessing the login page via mobile device when the default first letter is capitalized while the convention for username is usually only small letters

    Credit to Limor Eden for pointing me out for this issue

    opened by amitay87 8
  • Added the ability to modify message categories, disable messages

    Added the ability to modify message categories, disable messages

    Like the title suggests, this PR would allow users to set custom message categories and disable the messages from flask_simplelogin entirely. (See issue #17) This is done by replacing the string values in the messages dictionary with namedtuples (as recommended by @cuducos). The first value is the message string, the second is the category for flask to flash it as.

    This allows for some, interesting, modifications (as well as more practical ones if you use different categories in your project): Annotation 2019-10-25 181834 Annotation 2019-10-25 181759

    If the user sets messages=False flask_simplelogin will not flash any messages.

    There are still some issues that need to be worked on though:

    • As far as I can tell, the user needs to set up the namedtuple themselves
      from collections import namedtuple
      Message = namedtuple("Message","message category")
      

      for their app to use a custom dict. I wonder if there's a simple way...

    • There's no way to disable messages individually, which could be useful if you use a custom login checker, but want to keep other messages.
    • 'access_denied' and 'auth_error' don't currently use the namedtuple, which is somewhat unintuitive, but they don't have categories.
    • I'd like a second opinion on lines 183-184 (master) vs. 190-195 (message-improvements). The logic seems sound, but it feels like there should be a more pythonic way of doing it.
    • I haven't updated the README to reflect any of these changes yet.
    work in progress 
    opened by jforseth210 7
  • Lack of documentation regarding unit testing.

    Lack of documentation regarding unit testing.

    After putting it off for way too long, I've finally decided to teach myself unit testing with the unittest module and write some tests for my Flask project. I've run into a bit of a roadblock with the @login_required decorator though. I can't figure out how to test any of my views that require a login. For all of my other views, I'm able to use app.test_client(self).get() or .post() to make a request and run assertions on the response. However, I can't seem to get that to work with my login form since I don't have a valid csrf token. I saw that you had a similar test in test_app.py but I had some trouble modifying the session in my code, and I saw your comment:

    #token is still invalid :(

    leading me to believe that this was a dead end.

    Next, I searched this repo for references to csrf tokens, and didn't find anything. I realized that this was probably handled by WTForms, so I searched their docs for anything to do with testing, but the only thing I found was talking about recaptcha which didn't help me at all.

    I came back to this repo and noticed that there's the basic parameter for @login_required() so I tried to figure out a way to only enable basic logins when I was running a test. Modifying all of my @login_required decorators to accept a boolean seemed hacky, and I ran into circular import problems between my main file and my blueprints.

    At this point, I'm using the LiveServerTestCase from flask_testing with Selenium. It works, but running a whole browser is slow and seems hacky.

    The relevant code from my test file:

    import unittest
    import time
    from flask_testing import LiveServerTestCase
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from webtool import app
    
    # Doesn't work
    class FlaskTestCase(unittest.TestCase):
        def test_login(self):
            tester = app.test_client(self)
            response = tester.post(
                '/login/', data=dict(username='testing', password=PROJECT_PASSWORD, next='/'))
            # csrf token missing
    
    # Works but inefficent.
    class LiveServer(LiveServerTestCase):
        def create_app(self):
            app.config['TESTING'] = True
            app.config['LIVESERVER_PORT'] = 0
            return app
    
        def test_correct_login(self):
            driver = webdriver.Firefox()
            driver.get(self.get_server_url()+"/login")
            username_elem = driver.find_element_by_id('username')
            username_elem.send_keys(username)
            password_elem = driver.find_element_by_id('password')
            password_elem.send_keys(password)
            password_elem.send_keys(Keys.RETURN)
            time.sleep(2)  # Give it time to load
            self.assertTrue('Successful' in driver.page_source)
            driver.close()
    

    tl;dr: I can't figure out how to unit test views protected by @login_required(). I was able to get it working with Selenium, but it's too slow.

    opened by jforseth210 6
  • Making messages more customizable

    Making messages more customizable

    We are already able to customize the dictionary of messages simplelogin flashes. However, there is no easy way to:

    1. Toggle messages on and off
    2. Customize the categories of the flashes

    Toggling could be useful if the user has implemented a custom login checker function, or if the user doesn't want to flash these messages. Custom categories could be useful for projects structured with different categories. For example, if I have a project that uses: 'success' 'alert' 'info' 'warning' and I try to use flask_simplelogin, the categories: 'danger' 'primary' etc, could break an existing project structure.

    I suggest something along the lines of:

    show_messages = True
    

    that can be configured just like the message dictionary. Then, all flashes could be place inside an if statement, like this:

    if show_messages:
          flash(self.messages['someKey'], 'someCategory')
    

    I'm not quite as sure how custom categories would work. Parts of the source code went over my head. For all I know, this could already be possible. If so, I'd suggest some updates to the README to clarify. If not, maybe a nested dictionary could be used?

    messages = {
    'login-success', {'message':'someMessage', 'category':'someCategory'},
    }
    
    hacktoberfest good first issue 
    opened by jforseth210 6
  • start sample_app.py error

    start sample_app.py error

    i got the error when i try to run this app

    #python simple_app.py 
    Traceback (most recent call last):
      File "simple_app.py", line 39, in <module>
        @login_required(username=['chuck', 'mary'])
      File "/usr/local/python2.7/lib/python2.7/site-packages/flask_simplelogin/__init__.py", line 109, in login_required
        @wraps(function)
      File "/usr/local/python2.7/lib/python2.7/functools.py", line 33, in update_wrapper
        setattr(wrapper, attr, getattr(wrapped, attr))
    AttributeError: 'NoneType' object has no attribute '__module__'
    

    my env python version is

    # python -V
    Python 2.7.13 (default, Aug  9 2017, 23:25:57) 
    

    OS system: ** centos 6.5 64bit**

    then i also try run python manage.py runserver

    Traceback (most recent call last):
      File "manage.py", line 135, in <module>
        main()
      File "/usr/local/python2.7/lib/python2.7/site-packages/click/core.py", line 722, in __call__
        return self.main(*args, **kwargs)
      File "/usr/local/python2.7/lib/python2.7/site-packages/click/core.py", line 697, in main
        rv = self.invoke(ctx)
      File "/usr/local/python2.7/lib/python2.7/site-packages/click/core.py", line 1066, in invoke
        return _process_result(sub_ctx.command.invoke(sub_ctx))
      File "/usr/local/python2.7/lib/python2.7/site-packages/click/core.py", line 895, in invoke
        return ctx.invoke(self.callback, **ctx.params)
      File "/usr/local/python2.7/lib/python2.7/site-packages/click/core.py", line 535, in invoke
        return callback(*args, **kwargs)
      File "manage.py", line 89, in decorator
        configure_views(app)
      File "manage.py", line 66, in configure_views
        @login_required()
      File "/usr/local/python2.7/lib/python2.7/site-packages/flask_simplelogin/__init__.py", line 109, in login_required
        @wraps(function)
      File "/usr/local/python2.7/lib/python2.7/functools.py", line 33, in update_wrapper
        setattr(wrapper, attr, getattr(wrapped, attr))
    AttributeError: 'NoneType' object has no attribute '__module__'
    

    seems have the same problem

    opened by Linkding 4
  • New release?

    New release?

    PyPI has 0.7.0 and with some new features added e.g: new Message style looks like a new minor release is needed.

    https://github.com/flask-extensions/Flask-SimpleLogin/compare/0.0.7...main

    Time for a 0.1.0 ?

    I am currently installing from github but I will need to add this to an RPM package and then better to be on PyPI.

    opened by rochacbruno 3
  • Rename the repository

    Rename the repository

    Maybe it's just me (and my dear OCD), but what are the odds we might break something by renaming this repo Flask-SimpleLogin?

    image

    We might to update the documentation, update the Travis's URLs in the README.md and that's all, right?

    cc @Riverfount and, maybe, @rochacbruno

    opened by cuducos 3
  • simple_log soesn't work for blueprints

    simple_log soesn't work for blueprints

    Hey, great extension!

    I tried using simple_login, and it works great except, it does't work for paths added by blueprints.

    import flask
    import flask_simplelogin
    
    app = flask.Flask(__name__)
    
    my_blueprint = flask.Blueprint('BP', __name__)  # + some url_routes etc...
    app.register_blueprint(my_blueprint, url_prefix='/my_path')
    
    flask_simplelogin.SimpleLogin(app) # doesn't work for /my_path
    

    EDIT: sorry I probably misunderstood something here. I'll close this Thx again.

    opened by topper-123 3
  • csrf_token The CSRF token is invalid

    csrf_token The CSRF token is invalid

    I've hosted flask in heroku. When I login through desktop it's working but when I login through mobile, I get this error.

    Screenshot_20220821-163718_Brave.jpg

    After attempting once in mobile, the error continues in desktop too until I deploy fresh.

    what could have gone wrong?

    opened by gd03champ 2
  • Open redirect vulnerability

    Open redirect vulnerability

    First of all, thank you for the work! For the detail, there is an Open Redirect vulnerability in flask_simplelogin when authenticating after trying to access a page where the @login_required directive is set. An attacker can then send a link to : https://goodsite.com/login/?next=https://badsite.com/login -> The user authenticates and is then redirected to the wrong site with the same appearance (potentially) indicating for example "login failed", he then retypes his credentials and that's it for the attacker...

    I think it would be interesting to allow redirection only if the "next url" is "routable".

    opened by Guezone 2
  • Add a way to configurate login_url and logout_url

    Add a way to configurate login_url and logout_url

    Hola! Thanks for the app, it's really cool, simple and time-saving.

    I had a need to change some in-app variables (login_url, logout_url and home_url) and found it difficult because a method like this

    sl = SimpleLogin(app)
    sl.config['login_url'] = '/admin/login/'
    sl.config['logout_url'] = '/admin/logout/'
    sl.config['home_url'] = '/admin/'
    

    isn't working (views for login and logout are already registered at __init__) and changing blueprint url rules after that is a bit too hard.

    It would be great to have an ability to set this urls by writing something like this

    SIMPLELOGIN_LOGIN_URL = '/admin/login/'
    SIMPLELOGIN_LOGOUT_URL = '/admin/logout/'
    SIMPLELOGIN_HOME_URL = '/admin/'
    

    or this SimpleLogin(app, login_url='/admin/login/', logout_url='/admin/logout/', 'home_url'='/admin/')

    I could try to send a pull request, but not sure what method (or both) is better.

    enhancement hacktoberfest 
    opened by vvlch 2
  • Automate releases based on tags

    Automate releases based on tags

    Every time a new tag is pushed to main/master

    github actions can publish a new release.

    Example: https://github.com/rochacbruno/python-project-template/blob/main/.github/workflows/release.yml

    hacktoberfest 
    opened by rochacbruno 0
Releases(0.1.1)
Owner
Flask Extensions
A curated list (and repos) of Flask-Extensions
Flask Extensions
Awesome Django authorization, without the database

rules rules is a tiny but powerful app providing object-level permissions to Django, without requiring a database. At its core, it is a generic framew

1.6k Dec 30, 2022
Imia is an authentication library for Starlette and FastAPI (python 3.8+).

Imia Imia (belarussian for "a name") is an authentication library for Starlette and FastAPI (python 3.8+). Production status The library is considered

Alex Oleshkevich 91 Nov 24, 2022
Two factor authentication system using azure services and python language and its api's

FUTURE READY TALENT VIRTUAL INTERSHIP PROJECT PROJECT NAME - TWO FACTOR AUTHENTICATION SYSTEM Resources used: * Azure functions(python)

BHUSHAN SATISH DESHMUKH 1 Dec 10, 2021
REST implementation of Django authentication system.

djoser REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such

Sunscrapers 2.2k Jan 01, 2023
Script that provides your TESLA access_token and refresh_token

TESLA tokens This script helps you get your TESLA access_token and refresh_token in order to connect to third party applications (Teslamate, TeslaFi,

Bun-Ny TAN 3 Apr 28, 2022
FastAPI extension that provides JWT Auth support (secure, easy to use, and lightweight)

FastAPI JWT Auth Documentation: https://indominusbyte.github.io/fastapi-jwt-auth Source Code: https://github.com/IndominusByte/fastapi-jwt-auth Featur

Nyoman Pradipta Dewantara 468 Jan 01, 2023
Boilerplate/Starter Project for building RESTful APIs using Flask, SQLite, JWT authentication.

auth-phyton Boilerplate/Starter Project for building RESTful APIs using Flask, SQLite, JWT authentication. Setup Step #1 - Install dependencies $ pip

sandhika 0 Aug 03, 2022
A simple model based API maker written in Python and based on Django and Django REST Framework

Fast DRF Fast DRF is a small library for making API faster with Django and Django REST Framework. It's easy and configurable. Full Documentation here

Mohammad Ashraful Islam 18 Oct 05, 2022
Auth for use with FastAPI

FastAPI Auth Pluggable auth for use with FastAPI Supports OAuth2 Password Flow Uses JWT access and refresh tokens 100% mypy and test coverage Supports

David Montague 95 Jan 02, 2023
Implements authentication and authorization as FastAPI dependencies

FastAPI Security Implements authentication and authorization as dependencies in FastAPI. Features Authentication via JWT-based OAuth 2 access tokens a

Jacob Magnusson 111 Jan 07, 2023
Social auth made simple

Python Social Auth Python Social Auth is an easy-to-setup social authentication/registration mechanism with support for several frameworks and auth pr

Matías Aguirre 2.8k Dec 24, 2022
蓝鲸用户管理是蓝鲸智云提供的企业组织架构和用户管理解决方案,为企业统一登录提供认证源服务。

蓝鲸用户管理 简体中文 | English 蓝鲸用户管理是蓝鲸智云提供的企业组织架构和用户管理解决方案,为企业统一登录提供认证源服务。 总览 架构设计 代码目录 功能 支持多层级的组织架构管理 支持通过多种方式同步数据:OpenLDAP、Microsoft Active Directory(MAD)

腾讯蓝鲸 35 Dec 14, 2022
This app makes it extremely easy to build Django powered SPA's (Single Page App) or Mobile apps exposing all registration and authentication related functionality as CBV's (Class Base View) and REST (JSON)

Welcome to django-rest-auth Repository is unmaintained at the moment (on pause). More info can be found on this issue page: https://github.com/Tivix/d

Tivix 2.4k Jan 03, 2023
A generic, spec-compliant, thorough implementation of the OAuth request-signing logic

OAuthLib - Python Framework for OAuth1 & OAuth2 *A generic, spec-compliant, thorough implementation of the OAuth request-signing logic for Python 3.5+

OAuthlib 2.5k Jan 02, 2023
Django x Elasticsearch Templates

Django x Elasticsearch Requirements Python 3.7 Django = 3 Elasticsearch 7.15 Setup Elasticsearch Install via brew Install brew tap elastic/tap brew

Aji Pratama 0 May 22, 2022
OAuth2 goodies for the Djangonauts!

Django OAuth Toolkit OAuth2 goodies for the Djangonauts! If you are facing one or more of the following: Your Django app exposes a web API you want to

Jazzband 2.7k Dec 31, 2022
A Python inplementation for OAuth2

OAuth2-Python Discord Inplementation for OAuth2 login systems. This is a simple Python 'app' made to inplement in your programs that require (shitty)

Prifixy 0 Jan 06, 2022
Django-registration (redux) provides user registration functionality for Django websites.

Description: Django-registration provides user registration functionality for Django websites. maintainers: Macropin, DiCato, and joshblum contributor

Andrew Cutler 920 Jan 08, 2023
RSA Cryptography Authentication Proof-of-Concept

RSA Cryptography Authentication Proof-of-Concept This project was a request by Structured Programming lectures in Computer Science college. It runs wi

Dennys Marcos 1 Jan 22, 2022
Creation & manipulation of PyPI tokens

PyPIToken: Manipulate PyPI API tokens PyPIToken is an open-source Python 3.6+ library for generating and manipulating PyPI tokens. PyPI tokens are ver

Joachim Jablon 8 Nov 01, 2022