Restored ancient login flow
authorNicolas DURAND <nicolas.durand@iri.centrepompidou.fr>
Tue, 17 Feb 2015 12:07:08 +0100
changeset 44 5ab922a46f13
parent 43 6d0e2523e17d
child 45 1506da593f40
Restored ancient login flow
src/catedit/models.py
src/catedit/templates/home/login.html
src/catedit/views/home.py
--- a/src/catedit/models.py	Mon Feb 16 15:13:39 2015 +0100
+++ b/src/catedit/models.py	Tue Feb 17 12:07:08 2015 +0100
@@ -42,13 +42,13 @@
             self.cat_graph.add((self.this_category, RDF.ID, Literal(cat_id)))
 
             if label:
-                self.cat_graph.add((self.this_category,
-                                   RDFS.label,
-                                   Literal(label)))
+                self.cat_graph.add(
+                    (self.this_category, RDFS.label, Literal(label))
+                )
             if description:
-                self.cat_graph.add((self.this_category,
-                                   RDF.Description,
-                                   Literal(description)))
+                self.cat_graph.add(
+                    (self.this_category, RDF.Description, Literal(description))
+                )
 
             if other_properties:
                 for (predicate, obj) in other_properties:
--- a/src/catedit/templates/home/login.html	Mon Feb 16 15:13:39 2015 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,67 +0,0 @@
-{% extends "layout.html" %}
-{% if not session["user_logged"] or not session["user_can_edit"][current_repository] %}
-  {% set readonly="readonly" %}
-{% else %}
-  {% set readonly=False %}
-{% endif %}
-{% block title %} Catedit: Login {% endblock title %}
-{% block head %}
-  {{ super() }}
-{% endblock head %}
-{% block navbar_items %}
-  {{ super() }}
-  <li><a class="navbar-decorative">></a></li>
-  <li class="active"><a>Authentification</a></li>
-{% endblock navbar_items%}
-{% block repo_list %}
-  {{ super() }}
-{% endblock repo_list %}
-{% block page_content %}
-<h2> <b>CatEdit</b> - <small>Authentification</small></h2>
-{% if form.user_login.errors or form.user_password.errors %}
-<div class="alert alert-danger">
-  <strong>
-    <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
-    Erreur:
-  </strong>
-  Vous n'avez pas rempli certains champs obligatoires.
-</div>
-{% endif %}
-<div class="col-md-8">
-  <p>
-    <br>
-    Veuillez entrez votre nom d'utilisateur Github et mot de passe Github.
-  </p>
-  <form method="POST" action="{{url_for('home.login')}}" id="login_form" role="form">
-    <div class="form-group">
-      {% if form.user_login.errors %}
-        {% set login_placeholder="Champ obligatoire" %}
-      {% endif %}
-      {{ form.hidden_tag() }}
-      {{form.user_login.label}}
-      {{form.user_login(class="form-control", id="user_login", placeholder=login_placeholder)}}
-      {{form.user_password.label}}
-      {{form.user_password(class="form-control", id="user_password")}}
-    </div>
-    <button type="submit" class="btn btn-default">Me connecter à CatEdit</button>
-  </form>
-{% if form.user_login.data and not(form.user_login.errors or form.user_password.errors) %}
-  <br>
-  <div class="col-md-8 alert alert-info">
-    <p>
-      Il semble que vous utilisez CatEdit pour la première fois. Veuillez cliquer
-      sur le lien suivant pour vous authentifier sur Github afin de pouvoir utiliser CatEdit.
-    </p>
-    <p>
-      Si ça n'est pas la première fois que vous utilisez CatEdit, vérifiez que vous n'avez pas entré
-      un mauvais nom d'utilisateur/mot de passe. Note: Si vous souhaitez changer d'utilisateur,
-      n'oubliez pas auparavant de vous déconnecter de l'utilisateur courant sur <a href="http://github.com">Github</a>.<br><br>
-    </p>
-    <form method="POST" action="{{url_for('home.login_confirm')}}" id="confirm_form" role="form">
-      <input name="csrf_token" value="{{ csrf_token() }}" type="hidden">
-      <button type="submit" class="btn btn-default">M'authentifier sur Github</button>
-    </form>
-  </div>
-{% endif %}
-</div>
-{% endblock page_content%}
--- a/src/catedit/views/home.py	Mon Feb 16 15:13:39 2015 +0100
+++ b/src/catedit/views/home.py	Tue Feb 17 12:07:08 2015 +0100
@@ -27,118 +27,21 @@
     """
     return render_template("home/index.html")
 
-
-class LoginForm(Form):
-    """
-        Custom form class for commiting changes
-    """
-    user_login = StringField(
-        "Nom d'utilisateur Github",
-        validators=[DataRequired()]
-    )
-    user_password = PasswordField(
-        "Mot de passe Github",
-        validators=[DataRequired()]
-    )
-
-
-@module.route('/catedit-login', methods=["GET", "POST"])
+@module.route('/catedit-login', methods=["GET"])
 def login():
     """
-        Function that manages authentication (Github), login
-
-        Note: If Persistence is set to PersistenceToFile (categories stored
-        in local files, used for debugging), creates a mock user named
-        "FileEditUser"
+        Function called if the user is new or revoked the auth token
     """
     if not session.get("user_logged", False):
-        session["modified_categories"] = {
-            repo: {} for repo
-            in app.config["PERSISTENCE_CONFIG"]["REPOSITORY_LIST"]
-        }
-        session["deleted_categories"] = {
-            repo: {} for repo
-            in app.config["PERSISTENCE_CONFIG"]["REPOSITORY_LIST"]
-        }
-        if app.config["PERSISTENCE_CONFIG"]["METHOD"] == "PersistenceToGithub":
-            login_form = LoginForm(request.form)
-            if request.method == "GET":
-                # We'll render the login form
-                return render_template(
-                    "home/login.html",
-                    form=login_form,
-                )
-            elif request.method == "POST":
-                if login_form.validate_on_submit():
-                    # We'll try to get the auth token for given username
-                    try:
-                        auth_response = get(
-                            "https://api.github.com/"
-                            + "authorizations",
-                            auth=HTTPBasicAuth(
-                                login_form.user_login.data,
-                                login_form.user_password.data
-                            )
-                        )
-                        for auth in auth_response.json():
-                            if auth["app"]["client_id"] \
-                               == app.config["GITHUB_CLIENT_ID"]:
-                                session["user_code"] = auth["token"]
-                                session["user_logged"] = True
-                    except:
-                        logger.debug(
-                            "Error requesting authorizations for"
-                            + " user. Either the user is new to catedit, or "
-                            + "entered a wrong username/password"
-                        )
-                    logger.debug(str(github.get("rate_limit")["resources"]))
-                    logger.debug(
-                        "user token found by request: "
-                        + str(session.get("user_code", None))
-                    )
-                    if session.get("user_code", None) is None:
-                        # We didn't get it, so we direct the user to the login page
-                        # with a link to github oauth system
-                        return render_template(
-                            "home/login.html",
-                            form=login_form
-                        )
-                    else:
-                        # we did get it, so we redirect to callback function
-                        # to wrap up user auth
-                        return redirect(url_for('home.login_callback'))
-                else:
-                    # form didn't validate, so we send it back to user
-                    return render_template(
-                        "home/login.html",
-                        form=login_form
-                    )
-        elif app.config["PERSISTENCE_CONFIG"]["METHOD"] == "PersistenceToFile":
-            session["user_logged"] = True
-            session["user_can_edit"] = {}
-            session["user_can_edit"]["local"] = True
-            session["user_login"] = "FileEditUser"
-            return redirect(url_for('home.index'))
+        return github.authorize(
+            scope="repo",
+            redirect_uri=url_for('home.login_callback', _external=True)
+        )
     else:
         return redirect(url_for('home.index'))
 
 
-@module.route('/catedit-login-confirm', methods=["GET", "POST"])
-def login_confirm():
-    """
-        Function called if the user is new or revoked the auth token
-    """
-    if not session.get("user_logged", False):
-        if request.method == "POST":
-            return github.authorize(
-                scope="repo",
-                redirect_uri=url_for('home.login_callback', _external=True)
-            )
-    else:
-        return redirect(url_for('home.index'))
-
-
-@module.route('/catedit-callback')
+@module.route('/catedit-github-callback')
 @github.authorized_handler
 def login_callback(oauth_code):
     """