This commit is contained in:
choelzl 2022-08-14 12:00:26 +00:00 committed by GitHub
commit be847bbbd7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 222 additions and 0 deletions

View file

@ -295,6 +295,39 @@ https_only: false
##
#admins: [""]
##
## List of Enabled Authentication Backend
## If not provided falls back to enabling all
##
## Supported Values:
## - invidious
## - google
## - oauth
## - ldap (Not implemented !)
## - saml (Not implemented !)
##
## Default: ["invidious","google","oauth"]
##
# auth_type: ["oauth"]
##
## OAuth Configuration
##
## Notes:
## - Supports multiple OAuth backends
## - Requires external_port and domain to be configured
##
## Default: []
##
# oauth:
# - host: oauth.example.net
# auth_uri: /oauth/authorize/
# token_uri: /oauth/token/
# info_uri: /oauth/userinfo/
# client_id: CLIENT_ID
# client_secret: CLIENT_SECRET
# redirect_uri: https://invidious.example.net/login/oauth
# -----------------------------
# Background jobs

View file

@ -32,6 +32,9 @@ require "yaml"
require "compress/zip"
require "protodec/utils"
require "oauth2"
require "http/client"
require "./invidious/database/*"
require "./invidious/database/migrations/*"
require "./invidious/helpers/*"

View file

@ -8,6 +8,17 @@ struct DBConfig
property dbname : String
end
struct OAuthConfig
include YAML::Serializable
property host : String
property auth_uri : String
property token_uri : String
property info_uri : String
property client_id : String
property client_secret : String
end
struct ConfigPreferences
include YAML::Serializable
@ -123,6 +134,9 @@ class Config
# Use quic transport for youtube api
property use_quic : Bool = false
property auth_type : Array(String) = ["invidious", "google", "oauth"] of String
property oauth : Array(OAuthConfig) = [] of OAuthConfig
# Saved cookies in "name1=value1; name2=value2..." format
@[YAML::Field(converter: Preferences::StringToCookies)]
property cookies : HTTP::Cookies = HTTP::Cookies.new

View file

@ -0,0 +1,47 @@
def oauth_get(idx)
if HOST_URL == ""
raise Exception.new("Missing domain and port configuration")
end
if idx > CONFIG.oauth.size
raise Exception.new("Invalid OAuth Endpoint Index: " + idx.to_s)
end
if oauth = CONFIG.oauth[idx]
oauth_host = oauth.host
oauth_auth_uri = oauth.auth_uri
oauth_token_uri = oauth.token_uri
oauth_info_uri = oauth.info_uri
oauth_client_id = oauth.client_id
oauth_client_secret = oauth.client_secret
oauth_redirect_uri = HOST_URL + "/login/oauth/" + idx.to_s
OAuth2::Client.new(oauth_host, oauth_client_id, oauth_client_secret,
authorize_uri: oauth_auth_uri, token_uri: oauth_token_uri,
redirect_uri: oauth_redirect_uri)
else
raise Exception.new("Missing OAuth Config")
end
end
def oauth_auth(idx, authorization_code)
oauth_get(idx).get_access_token_using_authorization_code(authorization_code)
end
def oauth_info(idx, token)
if idx > CONFIG.oauth.size
raise Exception.new("Invalid OAuth Endpoint Index: " + idx.to_s)
end
if oauth = CONFIG.oauth[idx]
oauth_host = oauth.host
oauth_info_uri = oauth.info_uri
client = HTTP::Client.new(oauth_host, tls: true)
token.authenticate(client)
response = client.get oauth_info_uri
client.close
response.body
else
raise Exception.new("Missing OAuth Config")
end
end

View file

@ -21,6 +21,17 @@ module Invidious::Routes::Login
account_type = env.params.query["type"]?
account_type ||= "invidious"
if CONFIG.auth_type.find { |i| i == account_type } == nil
if CONFIG.auth_type.size == 0
account_type = "invidious"
else
account_type = CONFIG.auth_type[0]
end
end
oauth = CONFIG.auth_type.find { |i| i == "oauth" } && (CONFIG.oauth.size > 0)
oauth_providers = CONFIG.oauth
captcha_type = env.params.query["captcha"]?
captcha_type ||= "image"
@ -30,6 +41,68 @@ module Invidious::Routes::Login
templated "user/login"
end
def self.login_oauth(env)
locale = env.get("preferences").as(Preferences).locale
user = env.get? "user"
return env.redirect "/feed/subscriptions" if user
referer = get_referer(env, "/feed/subscriptions")
authorization_code = env.params.query["code"]?
provider_idx = env.params.url["provider"].to_i
if authorization_code
begin
token = oauth_auth(provider_idx, authorization_code)
info = JSON.parse(oauth_info(provider_idx, token))
email = info["email"].as_s
user = Invidious::Database::Users.select(email: email)
if user
sid = Base64.urlsafe_encode(Random::Secure.random_bytes(32))
Invidious::Database::SessionIDs.insert(sid, email)
env.response.cookies["SID"] = Invidious::User::Cookies.sid(CONFIG.domain, sid)
if env.request.cookies["PREFS"]?
cookie = env.request.cookies["PREFS"]
cookie.expires = Time.utc(1990, 1, 1)
env.response.cookies << cookie
end
else
sid = Base64.urlsafe_encode(Random::Secure.random_bytes(32))
user, sid = create_user(sid, email)
if language_header = env.request.headers["Accept-Language"]?
if language = ANG.language_negotiator.best(language_header, LOCALES.keys)
user.preferences.locale = language.header
end
end
Invidious::Database::Users.insert(user)
Invidious::Database::SessionIDs.insert(sid, email)
view_name = "subscriptions_#{sha256(user.email)}"
PG_DB.exec("CREATE MATERIALIZED VIEW #{view_name} AS #{MATERIALIZED_VIEW_SQL.call(user.email)}")
env.response.cookies["SID"] = Invidious::User::Cookies.sid(CONFIG.domain, sid)
if env.request.cookies["PREFS"]?
user.preferences = env.get("preferences").as(Preferences)
Invidious::Database::Users.update_preferences(user)
cookie = env.request.cookies["PREFS"]
cookie.expires = Time.utc(1990, 1, 1)
env.response.cookies << cookie
end
end
env.redirect referer
rescue
return error_template(403, "Invalid Authorization Code")
end
else
return error_template(403, "Missing Authorization Code")
end
end
def self.login(env)
locale = env.get("preferences").as(Preferences).locale
@ -42,10 +115,20 @@ module Invidious::Routes::Login
# https://stackoverflow.com/a/574698
email = env.params.body["email"]?.try &.downcase.byte_slice(0, 254)
password = env.params.body["password"]?
oauth = CONFIG.auth_type.find { |i| i == "oauth" } && (CONFIG.oauth.size > 0)
oauth_providers = CONFIG.oauth
account_type = env.params.query["type"]?
account_type ||= "invidious"
if CONFIG.auth_type.size == 0
return error_template(401, "No authentication backend enabled.")
end
if CONFIG.auth_type.find { |i| i == account_type } == nil
account_type = CONFIG.auth_type[0]
end
case account_type
when "google"
tfa_code = env.params.body["tfa"]?.try &.lchop("G-")
@ -308,6 +391,13 @@ module Invidious::Routes::Login
error_message = %(#{ex.message}<br/>Traceback:<br/><div style="padding-left:2em" id="traceback">#{traceback.gets_to_end}</div>)
return error_template(500, error_message)
end
when "oauth"
provider_idx = env.params.body["provider"].to_i
env.redirect oauth_get(provider_idx).get_authorize_uri("openid email profile")
when "saml"
return error_template(500, "Not implemented")
when "ldap"
return error_template(500, "Not implemented")
when "invidious"
if !email
return error_template(401, "User ID is a required field")

View file

@ -53,6 +53,7 @@ module Invidious::Routing
def register_user_routes
# User login/out
get "/login", Routes::Login, :login_page
get "/login/oauth/:provider", Routes::Login, :login_oauth
post "/login", Routes::Login, :login
post "/signout", Routes::Login, :signout
get "/Captcha", Routes::Login, :captcha

View file

@ -14,6 +14,7 @@ struct Invidious::User
return HTTP::Cookie.new(
name: "SID",
domain: domain,
path: "/",
value: sid,
expires: Time.utc + 2.years,
secure: SECURE,
@ -28,6 +29,7 @@ struct Invidious::User
return HTTP::Cookie.new(
name: "PREFS",
domain: domain,
path: "/",
value: URI.encode_www_form(preferences.to_json),
expires: Time.utc + 2.years,
secure: SECURE,

View file

@ -72,6 +72,24 @@ def fetch_user(sid, headers)
return user, sid
end
def create_user(sid, email)
token = Base64.urlsafe_encode(Random::Secure.random_bytes(32))
user = Invidious::User.new({
updated: Time.utc,
notifications: [] of String,
subscriptions: [] of String,
email: email,
preferences: Preferences.new(CONFIG.default_user_preferences.to_tuple),
password: nil,
token: token,
watched: [] of String,
feed_needs_update: true,
})
return user, sid
end
def create_user(sid, email, password)
password = Crypto::Bcrypt::Password.create(password, cost: 10)
token = Base64.urlsafe_encode(Random::Secure.random_bytes(32))

View file

@ -43,6 +43,17 @@
<button type="submit" class="pure-button pure-button-primary"><%= translate(locale, "Sign In") %></button>
</fieldset>
</form>
<% when "oauth" %>
<form class="pure-form pure-form-stacked" action="/login?referer=<%= URI.encode_www_form(referer) %>&type=oauth" method="post">
<fieldset>
<select name="provider" id="provider">
<% oauth_providers.each_index do |idx| %>
<option value="<%= idx %>"><%= oauth_providers[idx].host %></option>
<% end %>
</select>
<button type="submit" class="pure-button pure-button-primary"><%= translate(locale, "Sign In via OAuth") %></button>
</fieldset>
</form>
<% else # "invidious" %>
<form class="pure-form pure-form-stacked" action="/login?referer=<%= URI.encode_www_form(referer) %>&type=invidious" method="post">
<fieldset>
@ -104,6 +115,9 @@
<%= translate(locale, "Sign In") %>/<%= translate(locale, "Register") %>
</button>
<% end %>
<% if oauth %>
<a class="pure-button pure-button-secondary" href="/login?referer=<%= URI.encode_www_form(referer) %>&type=oauth">OAuth</a>
<% end %>
</fieldset>
</form>
<% end %>