aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/HttpServer/Security/AuthService.cs
blob: dde61079b90d9a83b3622fcbf7d354367fcfdf5b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Connect;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
using ServiceStack;
using ServiceStack.Auth;
using ServiceStack.Web;
using System;
using System.Collections.Specialized;
using System.Linq;

namespace MediaBrowser.Server.Implementations.HttpServer.Security
{
    public class AuthService : IAuthService
    {
        private readonly IServerConfigurationManager _config;

        public AuthService(IUserManager userManager, ISessionManager sessionManager, IAuthorizationContext authorizationContext, IServerConfigurationManager config, IConnectManager connectManager)
        {
            AuthorizationContext = authorizationContext;
            _config = config;
            ConnectManager = connectManager;
            SessionManager = sessionManager;
            UserManager = userManager;
        }

        public IUserManager UserManager { get; private set; }
        public ISessionManager SessionManager { get; private set; }
        public IAuthorizationContext AuthorizationContext { get; private set; }
        public IConnectManager ConnectManager { get; private set; }

        /// <summary>
        /// Restrict authentication to a specific <see cref="IAuthProvider"/>.
        /// For example, if this attribute should only permit access
        /// if the user is authenticated with <see cref="BasicAuthProvider"/>,
        /// you should set this property to <see cref="BasicAuthProvider.Name"/>.
        /// </summary>
        public string Provider { get; set; }

        /// <summary>
        /// Redirect the client to a specific URL if authentication failed.
        /// If this property is null, simply `401 Unauthorized` is returned.
        /// </summary>
        public string HtmlRedirect { get; set; }

        public void Authenticate(IRequest request,
            IResponse response,
            object requestDto,
            IAuthenticated authAttribtues)
        {
            if (HostContext.HasValidAuthSecret(request))
                return;

            //ExecuteBasic(req, res, requestDto); //first check if session is authenticated
            //if (res.IsClosed) return; //AuthenticateAttribute already closed the request (ie auth failed)

            ValidateUser(request, response, authAttribtues);
        }

        private void ValidateUser(IRequest req, IResponse response, IAuthenticated authAttribtues)
        {
            // This code is executed before the service
            var auth = AuthorizationContext.GetAuthorizationInfo(req);

            if (!string.IsNullOrWhiteSpace(auth.Token) ||
                !_config.Configuration.InsecureApps6.Contains(auth.Client ?? string.Empty, StringComparer.OrdinalIgnoreCase))
            {
                var valid = IsValidConnectKey(auth.Token);

                if (!valid)
                {
                    SessionManager.ValidateSecurityToken(auth.Token);
                }
            }

            var user = string.IsNullOrWhiteSpace(auth.UserId)
                ? null
                : UserManager.GetUserById(auth.UserId);

            if (user == null & !string.IsNullOrWhiteSpace(auth.UserId))
            {
                throw new ArgumentException("User with Id " + auth.UserId + " not found");
            }

            if (user != null)
            {
                if (user.Configuration.IsDisabled)
                {
                    throw new AuthenticationException("User account has been disabled.");
                }

                if (!user.Configuration.IsAdministrator &&
                    !authAttribtues.EscapeParentalControl &&
                    !user.IsParentalScheduleAllowed())
                {
                    response.AddHeader("X-Application-Error-Code", "ParentalControl");
                    throw new AuthenticationException("This user account is not allowed access at this time.");
                }
            }

            var roles = authAttribtues.GetRoles().ToList();

            if (roles.Contains("admin", StringComparer.OrdinalIgnoreCase))
            {
                if (user == null || !user.Configuration.IsAdministrator)
                {
                    throw new ArgumentException("Administrative access is required for this request.");
                }
            }

            if (!string.IsNullOrWhiteSpace(auth.DeviceId) &&
                !string.IsNullOrWhiteSpace(auth.Client) &&
                !string.IsNullOrWhiteSpace(auth.Device))
            {
                SessionManager.LogSessionActivity(auth.Client,
                    auth.Version,
                    auth.DeviceId,
                    auth.Device,
                    req.RemoteIp,
                    user);
            }
        }

        private bool IsValidConnectKey(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }

            return ConnectManager.IsAuthorizationTokenValid(token);
        }

        protected bool DoHtmlRedirectIfConfigured(IRequest req, IResponse res, bool includeRedirectParam = false)
        {
            var htmlRedirect = this.HtmlRedirect ?? AuthenticateService.HtmlRedirect;
            if (htmlRedirect != null && req.ResponseContentType.MatchesContentType(MimeTypes.Html))
            {
                DoHtmlRedirect(htmlRedirect, req, res, includeRedirectParam);
                return true;
            }
            return false;
        }

        public static void DoHtmlRedirect(string redirectUrl, IRequest req, IResponse res, bool includeRedirectParam)
        {
            var url = req.ResolveAbsoluteUrl(redirectUrl);
            if (includeRedirectParam)
            {
                var absoluteRequestPath = req.ResolveAbsoluteUrl("~" + req.PathInfo + ToQueryString(req.QueryString));
                url = url.AddQueryParam(HostContext.ResolveLocalizedString(LocalizedStrings.Redirect), absoluteRequestPath);
            }

            res.RedirectToUrl(url);
        }

        private static string ToQueryString(INameValueCollection queryStringCollection)
        {
            return ToQueryString((NameValueCollection)queryStringCollection.Original);
        }

        private static string ToQueryString(NameValueCollection queryStringCollection)
        {
            if (queryStringCollection == null || queryStringCollection.Count == 0)
                return String.Empty;

            return "?" + queryStringCollection.ToFormUrlEncoded();
        }
    }
}