splent-feature-github 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1 @@
1
+ splent_io
@@ -0,0 +1,30 @@
1
+ from splent_framework.assets.asset_registry import register_asset
2
+ from splent_framework.blueprints.base_blueprint import create_blueprint
3
+ from splent_framework.refinement import refine_model
4
+ from splent_framework.services.service_locator import register_service
5
+
6
+ from splent_io.splent_feature_github.models import UserProfileGithubMixin
7
+ from splent_io.splent_feature_github.services import (
8
+ GithubService,
9
+ register_github_client,
10
+ )
11
+
12
+ github_bp = create_blueprint(__name__)
13
+
14
+
15
+ def init_feature(app):
16
+ from splent_io.splent_feature_github.config import inject_config
17
+
18
+ inject_config(app)
19
+ register_service(app, "GithubService", GithubService)
20
+ register_github_client(app)
21
+ refine_model("UserProfile", UserProfileGithubMixin)
22
+ # GitHub's colours on its button and its profile row, for the public
23
+ # shell. The app shell gets the same file through layout.head.css.
24
+ register_asset(
25
+ "css", "github.assets", order=100, subfolder="css", filename="github.css"
26
+ )
27
+
28
+
29
+ def inject_context_vars(app):
30
+ return {}
@@ -0,0 +1,70 @@
1
+ /* GitHub's colours, wherever the product draws GitHub: its sign-in button
2
+ on the login and sign-up pages, and the linked account on the profile
3
+ page.
4
+
5
+ The public shell loads this file from the asset registry and the app
6
+ shell through its layout.head.css slot, after their own stylesheets. A
7
+ product that wants another look overrides these selectors in a
8
+ stylesheet of its own. */
9
+
10
+ /* The sign-in button. Every state is set, so the button stays GitHub's
11
+ whatever a shell does to a bare .btn on hover or focus. The variables are
12
+ the ones Bootstrap 5.3 reads, and the properties serve the shells that do
13
+ not read them. */
14
+ .btn.btn-github,
15
+ .btn.btn-github:hover,
16
+ .btn.btn-github:focus,
17
+ .btn.btn-github:focus-visible,
18
+ .btn.btn-github:active {
19
+ --bs-btn-color: #fff;
20
+ --bs-btn-bg: #24292f;
21
+ --bs-btn-border-color: #24292f;
22
+ --bs-btn-hover-color: #fff;
23
+ --bs-btn-hover-bg: #1a1e23;
24
+ --bs-btn-hover-border-color: #1a1e23;
25
+ --bs-btn-active-color: #fff;
26
+ --bs-btn-active-bg: #1a1e23;
27
+ --bs-btn-active-border-color: #1a1e23;
28
+ color: #fff;
29
+ background-color: #24292f;
30
+ border-color: #24292f;
31
+ }
32
+
33
+ .btn.btn-github:hover,
34
+ .btn.btn-github:focus-visible,
35
+ .btn.btn-github:active {
36
+ background-color: #1a1e23;
37
+ border-color: #1a1e23;
38
+ }
39
+
40
+ /* The GitHub mark, drawn in currentColor. */
41
+ .github-mark {
42
+ color: #212529;
43
+ flex-shrink: 0;
44
+ }
45
+
46
+ /* The profile row: the linked account in a field that reads as fixed, or a
47
+ link to connect one that looks like the same field. */
48
+ .form-control.github-identity__field {
49
+ background-color: #f8f9fa;
50
+ }
51
+
52
+ .form-control.github-identity__connect {
53
+ color: #495057;
54
+ cursor: pointer;
55
+ }
56
+
57
+ .github-identity__value {
58
+ flex-grow: 1;
59
+ }
60
+
61
+ .btn.github-identity__disconnect,
62
+ .btn.github-identity__disconnect:hover,
63
+ .btn.github-identity__disconnect:focus,
64
+ .btn.github-identity__disconnect:focus-visible,
65
+ .btn.github-identity__disconnect:active {
66
+ background: none;
67
+ border: none;
68
+ color: #212529;
69
+ cursor: pointer;
70
+ }
@@ -0,0 +1,18 @@
1
+ """
2
+ github feature configuration.
3
+
4
+ The OAuth app registered at https://github.com/settings/developers.
5
+ Without both values GitHub sign-in is disabled (the redirect fails and the
6
+ user is sent back to the login page with a message).
7
+ """
8
+
9
+ import os
10
+
11
+
12
+ def inject_config(app):
13
+ app.config.update(
14
+ {
15
+ "GITHUB_CLIENT_ID": os.getenv("GITHUB_CLIENT_ID", ""),
16
+ "GITHUB_CLIENT_SECRET": os.getenv("GITHUB_CLIENT_SECRET", ""),
17
+ }
18
+ )
@@ -0,0 +1,58 @@
1
+ """Template hooks for splent_feature_github.
2
+
3
+ GitHub offers itself first on the login page (auth's auth.login.providers)
4
+ and on the sign-up page when the product has one (signup's
5
+ signup.providers). On the edit-profile page it shows the linked account, or
6
+ a "Connect GitHub" link, first among the sections below the form
7
+ (profile's profile.edit.sections).
8
+
9
+ Every slot is filled by name, so a product without signup simply has no
10
+ sign-up page to show the button on.
11
+
12
+ GitHub's colours are in assets/css/github.css. The public shell loads it
13
+ from the asset registry (see __init__.py), and the app shell, which does not
14
+ render the registry, through its layout.head.css slot.
15
+ """
16
+
17
+ from flask import render_template, request, url_for
18
+ from flask_login import current_user
19
+ from markupsafe import Markup
20
+
21
+ from splent_framework.hooks.template_hooks import register_template_hook
22
+
23
+ # Before ORCID, which takes 20, in every slot both of them fill.
24
+ ORDER = 10
25
+
26
+
27
+ def github_login_button():
28
+ from splent_io.splent_feature_auth.routes import safe_next_url
29
+
30
+ # The login and the sign-up both carry where the reader was heading, in
31
+ # the query string and, after a failed post, in their form.
32
+ next_url = safe_next_url(request.form.get("next") or request.args.get("next"))
33
+ return render_template("hooks/github_login_button.html", next_url=next_url)
34
+
35
+
36
+ def github_profile_row():
37
+ from splent_io.splent_feature_identities.services import IdentitiesService
38
+
39
+ identity = next(
40
+ (
41
+ i
42
+ for i in IdentitiesService().identities_of(current_user.id)
43
+ if i.provider == "github"
44
+ ),
45
+ None,
46
+ )
47
+ return render_template("hooks/github_profile_row.html", identity=identity)
48
+
49
+
50
+ def github_stylesheet():
51
+ href = url_for("github.assets", subfolder="css", filename="github.css")
52
+ return Markup(f'<link rel="stylesheet" href="{href}">')
53
+
54
+
55
+ register_template_hook("auth.login.providers", github_login_button, order=ORDER)
56
+ register_template_hook("signup.providers", github_login_button, order=ORDER)
57
+ register_template_hook("profile.edit.sections", github_profile_row, order=ORDER)
58
+ register_template_hook("layout.head.css", github_stylesheet)
@@ -0,0 +1,36 @@
1
+ [alembic]
2
+ script_location = migrations
3
+
4
+ [loggers]
5
+ keys = root,sqlalchemy,alembic
6
+
7
+ [handlers]
8
+ keys = console
9
+
10
+ [formatters]
11
+ keys = generic
12
+
13
+ [logger_root]
14
+ level = WARN
15
+ handlers = console
16
+ qualname =
17
+
18
+ [logger_sqlalchemy]
19
+ level = WARN
20
+ handlers =
21
+ qualname = sqlalchemy.engine
22
+
23
+ [logger_alembic]
24
+ level = INFO
25
+ handlers =
26
+ qualname = alembic
27
+
28
+ [handler_console]
29
+ class = StreamHandler
30
+ args = (sys.stderr,)
31
+ level = NOTSET
32
+ formatter = generic
33
+
34
+ [formatter_generic]
35
+ format = %(levelname)-5.5s [%(name)s] %(message)s
36
+ datefmt = %H:%M:%S
@@ -0,0 +1,9 @@
1
+ """Alembic migration environment for splent_feature_github."""
2
+
3
+ from splent_io.splent_feature_github import models # noqa
4
+ from splent_framework.migrations.feature_env import run_feature_migrations
5
+
6
+ FEATURE_NAME = "splent_feature_github"
7
+ FEATURE_TABLES = set()
8
+
9
+ run_feature_migrations(FEATURE_NAME, FEATURE_TABLES)
@@ -0,0 +1,24 @@
1
+ """${message}
2
+
3
+ Revision ID: ${up_revision}
4
+ Revises: ${down_revision | comma,n}
5
+ Create Date: ${create_date}
6
+
7
+ """
8
+ from alembic import op
9
+ import sqlalchemy as sa
10
+ ${imports if imports else ""}
11
+
12
+ # revision identifiers, used by Alembic.
13
+ revision = ${repr(up_revision)}
14
+ down_revision = ${repr(down_revision)}
15
+ branch_labels = ${repr(branch_labels)}
16
+ depends_on = ${repr(depends_on)}
17
+
18
+
19
+ def upgrade():
20
+ ${upgrades if upgrades else "pass"}
21
+
22
+
23
+ def downgrade():
24
+ ${downgrades if downgrades else "pass"}
@@ -0,0 +1,43 @@
1
+ """splent_feature_github
2
+
3
+ Revision ID: 7ace6050fb3f
4
+ Revises:
5
+ Create Date: 2026-10-14 23:44:44.935160
6
+
7
+ """
8
+
9
+ from alembic import op
10
+ import sqlalchemy as sa
11
+
12
+
13
+ # revision identifiers, used by Alembic.
14
+ revision = "7ace6050fb3f"
15
+ down_revision = None
16
+ branch_labels = None
17
+ depends_on = None
18
+
19
+
20
+ def upgrade():
21
+ # ### commands auto generated by Alembic - please adjust! ###
22
+ op.create_table(
23
+ "github",
24
+ sa.Column("id", sa.Integer(), nullable=False),
25
+ sa.Column("github_id", sa.Integer(), nullable=False),
26
+ sa.Column("github_login", sa.String(length=255), nullable=False),
27
+ sa.Column("registration_date", sa.DateTime(), nullable=False),
28
+ sa.Column("profile_id", sa.Integer(), nullable=True),
29
+ sa.ForeignKeyConstraint(
30
+ ["profile_id"],
31
+ ["user_profile.id"],
32
+ ),
33
+ sa.PrimaryKeyConstraint("id"),
34
+ sa.UniqueConstraint("github_id"),
35
+ sa.UniqueConstraint("profile_id"),
36
+ )
37
+ # ### end Alembic commands ###
38
+
39
+
40
+ def downgrade():
41
+ # ### commands auto generated by Alembic - please adjust! ###
42
+ op.drop_table("github")
43
+ # ### end Alembic commands ###
@@ -0,0 +1,31 @@
1
+ from datetime import datetime
2
+
3
+ import pytz
4
+ from splent_framework.db import db
5
+
6
+
7
+ class Github(db.Model):
8
+ """The GitHub account on a user's profile.
9
+
10
+ The table keeps the name and columns of the application this feature was
11
+ ported from, so an existing database carries over as is.
12
+ """
13
+
14
+ id = db.Column(db.Integer, primary_key=True)
15
+ github_id = db.Column(db.Integer, unique=True, nullable=False)
16
+ github_login = db.Column(db.String(255), nullable=False)
17
+ registration_date = db.Column(
18
+ db.DateTime, nullable=False, default=lambda: datetime.now(pytz.utc)
19
+ )
20
+ profile_id = db.Column(db.Integer, db.ForeignKey("user_profile.id"), unique=True)
21
+
22
+ def __repr__(self):
23
+ return f"Github<{self.github_login}>"
24
+
25
+
26
+ class UserProfileGithubMixin:
27
+ """profile.get_github(), applied to profile's UserProfile."""
28
+
29
+ def get_github(self):
30
+ record = Github.query.filter_by(profile_id=self.id).first()
31
+ return record.github_login if record else None
@@ -0,0 +1,11 @@
1
+ from splent_framework.repositories.BaseRepository import BaseRepository
2
+
3
+ from splent_io.splent_feature_github.models import Github
4
+
5
+
6
+ class GithubRepository(BaseRepository):
7
+ def __init__(self):
8
+ super().__init__(Github)
9
+
10
+ def get_by_github_id(self, github_id: int) -> Github | None:
11
+ return self.model.query.filter_by(github_id=github_id).first()
@@ -0,0 +1,110 @@
1
+ from flask import current_app, flash, redirect, request, session, url_for
2
+ from flask_login import current_user, login_user
3
+ from splent_framework.services.service_locator import service_proxy
4
+
5
+ from splent_io.splent_feature_auth.decorators import login_required
6
+ from splent_io.splent_feature_auth.routes import landing_url, safe_next_url
7
+ from splent_io.splent_feature_github import github_bp
8
+
9
+ github_service = service_proxy("GithubService")
10
+
11
+
12
+ def _back_to_login(next_url):
13
+ return redirect(
14
+ url_for("auth.login", next=next_url) if next_url else url_for("auth.login")
15
+ )
16
+
17
+
18
+ @github_bp.route("/github/login")
19
+ def login():
20
+ next_url = safe_next_url(request.form.get("next") or request.args.get("next"))
21
+ if next_url:
22
+ session["github_next_url"] = next_url
23
+ else:
24
+ session.pop("github_next_url", None)
25
+
26
+ redirect_uri = url_for("github.authorize", _external=True)
27
+
28
+ try:
29
+ return github_service.github_client.authorize_redirect(redirect_uri)
30
+ except Exception as exc:
31
+ current_app.logger.exception("GitHub authorize_redirect failed: %s", exc)
32
+ flash("GitHub login failed. Please try again.", "danger")
33
+ return _back_to_login(next_url)
34
+
35
+
36
+ @github_bp.route("/github/authorize")
37
+ def authorize():
38
+ next_url = safe_next_url(session.pop("github_next_url", None))
39
+ connect_mode = session.pop("github_connect_mode", False)
40
+
41
+ # One instance for the whole callback: the proxy builds a new one on
42
+ # every attribute access.
43
+ service = github_service._get_current_object()
44
+
45
+ try:
46
+ token = service.github_client.authorize_access_token()
47
+ except Exception as exc:
48
+ current_app.logger.exception("GitHub authorize_access_token failed: %s", exc)
49
+ flash(
50
+ "GitHub authorization failed (invalid session or provider error). Please try again.",
51
+ "danger",
52
+ )
53
+ return _back_to_login(next_url)
54
+
55
+ user_info, err = service.get_github_user_info(token)
56
+ if err:
57
+ flash(err, "danger")
58
+ return _back_to_login(next_url)
59
+
60
+ if connect_mode:
61
+ if not current_user.is_authenticated:
62
+ flash("You must be logged in to connect GitHub.", "danger")
63
+ return redirect(url_for("auth.login"))
64
+
65
+ _, err = service.link_identity(current_user, user_info)
66
+ if err:
67
+ flash(err, "danger")
68
+ return redirect(url_for("profile.edit_profile"))
69
+
70
+ flash("GitHub account connected successfully", "success")
71
+ return redirect(url_for("profile.edit_profile"))
72
+
73
+ github_id = user_info.get("id")
74
+ if not service.identities.get_identity("github", github_id):
75
+ # Linked to nobody, so this sign-in would open an account. A product
76
+ # without signup refuses it here, whatever GitHub shared.
77
+ refusal = service.new_account_refusal()
78
+ if refusal:
79
+ flash(refusal, "danger")
80
+ return _back_to_login(next_url)
81
+
82
+ # get_github_user_info already falls back to the verified primary
83
+ # email; if GitHub still gave us nothing, bounce to login rather than
84
+ # create an account without an email.
85
+ if not user_info.get("email"):
86
+ flash(
87
+ "GitHub did not share a verified email, so we could not create your account. "
88
+ "Make a primary email verified on GitHub, or sign in with email or ORCID.",
89
+ "danger",
90
+ )
91
+ return _back_to_login(next_url)
92
+
93
+ user, err = service.get_or_create_user(user_info)
94
+ if err:
95
+ flash(err, "danger")
96
+ return _back_to_login(next_url)
97
+
98
+ login_user(user)
99
+ flash("Signed in with GitHub.", "success")
100
+ return redirect(next_url or landing_url())
101
+
102
+
103
+ # ── Connecting GitHub to the signed-in account ───────────────────────────────
104
+
105
+
106
+ @github_bp.route("/account/connect/github")
107
+ @login_required
108
+ def connect_github():
109
+ session["github_connect_mode"] = True
110
+ return redirect(url_for("github.login"))