1+ # frozen_string_literal: true
2+
3+ module Code0
4+ module Identities
5+ module Provider
6+ class Saml
7+ attr_reader :config_loader
8+
9+ def initialize ( config_loader )
10+ @config_loader = config_loader
11+ end
12+
13+ def authorization_url
14+ request = OneLogin ::RubySaml ::Authrequest . new
15+ request . create ( create_settings )
16+
17+ request . instance_variable_get :@login_url
18+ end
19+
20+ def load_identity ( **params )
21+ response = OneLogin ::RubySaml ::Response . new ( params [ :SAMLResponse ] , { **config [ :response_settings ] , settings : create_settings } )
22+ attributes = response . attributes
23+
24+ Identity . new ( config [ :provider_name ] ,
25+ response . name_id ,
26+ find_attribute ( attributes , config [ :attribute_statements ] [ :username ] ) ,
27+ find_attribute ( attributes , config [ :attribute_statements ] [ :email ] ) ,
28+ find_attribute ( attributes , config [ :attribute_statements ] [ :firstname ] ) ,
29+ find_attribute ( attributes , config [ :attribute_statements ] [ :lastname ] )
30+ )
31+ end
32+
33+ private
34+
35+ def find_attribute ( attributes , attribute_statements )
36+ attribute_statements . each do |statement |
37+ unless attributes [ statement ] . nil?
38+ return attributes [ statement ]
39+ end
40+ end
41+ nil
42+ end
43+
44+ def create_settings
45+ if config [ :metadata_url ] . nil?
46+ settings = OneLogin ::RubySaml ::Settings . new
47+ else
48+ idp_metadata_parser = OneLogin ::RubySaml ::IdpMetadataParser . new
49+ settings = idp_metadata_parser . parse_remote ( config [ :metadata_url ] )
50+ end
51+
52+ settings . name_identifier_format = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"
53+
54+ config [ :settings ] . each do |key , value |
55+ settings . send ( :"#{ key } =" , value )
56+ end
57+ settings
58+ end
59+
60+ def config
61+ config = config_loader
62+ if config_loader . is_a? ( Proc )
63+ config = config_loader . call
64+ end
65+
66+ config [ :provider_name ] ||= :saml
67+ config [ :response_settings ] ||= { }
68+ config [ :settings ] ||= { }
69+ config [ :attribute_statements ] ||= { }
70+ config [ :attribute_statements ] [ :username ] ||= %w[ username name http://schemas.goauthentik.io/2021/02/saml/username ]
71+ config [ :attribute_statements ] [ :email ] ||= %w[ email mail http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress http://schemas.microsoft.com/ws/2008/06/identity/claims/emailaddress ]
72+ config [ :attribute_statements ] [ :firstname ] ||= %w[ first_name firstname firstName http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname http://schemas.microsoft.com/ws/2008/06/identity/claims/givenname ]
73+ config [ :attribute_statements ] [ :lastname ] ||= %w[ last_name lastname lastName http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname http://schemas.microsoft.com/ws/2008/06/identity/claims/surname ]
74+
75+ config
76+ end
77+ end
78+ end
79+ end
80+ end
0 commit comments