All files / src/react-components auth.js

100% Statements 52/52
89.13% Branches 41/46
100% Functions 11/11
100% Lines 52/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293                                                                                      1x 1x 1x 1x                                                 23x                                 4x 4x   4x   1x       3x               5x   1x 1x     4x   2x   2x   2x   2x   2x   1x   1x                       6x 6x 6x                                               33x 33x 33x                                                                       93x 93x 93x               93x   3x   90x   2x   2x   2x   1x   1x   1x         90x 90x   1x   90x   1x                 7x   7x               95x   78x       17x   95x   92x                 3x                              
/*
 * Part of Pleiar.no - a collection of tools for nurses
 *
 * Copyright (C) Fagforbundet 2019
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
 
// @flow
 
// Let flow know about our AUTH_URL and AUTH_APPID globals (from webpack/data config)
declare var AUTH_URL:string;
declare var AUTH_APPID:string;
 
import * as React from 'react';
import { Button, Row, Col } from 'reactstrap';
import { Redirect } from 'react-router-dom';
import { StructuredData } from './shared/structured-data';
import { ExternalLink } from './shared/links';
import { MainContainer, PageTitle } from './layout';
import auth from '../auth';
import type { AuthError } from '../auth';
 
/**
 * Displays an "authentication failed" message
 */
class AuthFailed extends React.PureComponent<{| token: string |}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        const { token } = this.props;
        const error: AuthError | null = auth.getError();
        const errorCode: AuthError | "(ukjent)" = (error === null ? "(ukjent)" : error);
        return <MainContainer app="auth">
            <PageTitle />
            <Row>
                <Col>
                    <h3>Innloggingsfeil :(</h3>
                    Vi klarte ikke å logge deg inn. Du kan <ExternalLink sameWindow={true} href={getAuthURL()}>prøve på nytt</ExternalLink>.<br />
                    Hvis du fremdeles får feilmeldingen, send oss en e-post på <ExternalLink sameWindow={true} href="mailto:kontakt@pleiar.no">kontakt@pleiar.no</ExternalLink>. Ta gjerne med feilkoden som står nedenfor så skal vi undersøke og fikse problemet!<br /><br />
                </Col>
            </Row>
            <Row>
                <Col>
                    <code>
                        Feilkode: {errorCode} <span className="err-token">({token})</span>
                    </code>
                </Col>
            </Row>
        </MainContainer>;
    }
}
 
/**
 * Generates an authentication URL that can be used to log in
 */
function getAuthURL (): string
{
    return AUTH_URL+'?return_to='+location.origin+'/auth&app_id='+AUTH_APPID;
}
 
/**
 * Handler for /auth
 *
 * This handles passing JWT's to the auth object, and preforming redirects as
 * needed.
 */
class Authenticator extends React.PureComponent<{||}>
{
    /**
     * Redirects, using react-router-dom's `Redirect` to
     * localStorage.pleiarAuthRedirect or /
     */
    redirect (): React.Node
    {
        const redirect = window.localStorage.pleiarAuthRedirect;
        delete window.localStorage.pleiarAuthRedirect;
        // Verify that the redirect is valid(ish)
        if (/^\//.test(redirect) && /^(\/|\w|\d)*$/.test(redirect))
        {
            return <Redirect to={redirect} />;
        }
        else
        {
            return <Redirect to="/" />;
        }
    }
 
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        // Hack to permit logging out
        if(/^\/auth\/logout/.test(location.pathname))
        {
            auth.invalidate();
            return this.redirect();
        }
 
        if(auth.isAuthenticated())
        {
            return this.redirect();
        }
        const token = location.href.replace(/.+\/auth\/?\?jwt=/,'');
        // eslint-disable-next-line security/detect-possible-timing-attacks
        Eif(token !== location.href)
        {
            auth.authenticate(token);
        }
        if(auth.isAuthenticated())
        {
            return this.redirect();
        }
        return <AuthFailed token={token} />;
    }
}
 
/**
 * Renders an authentication overlay, which requests that the user log in.
 */
class AuthOverlay extends React.PureComponent<{||}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        window.localStorage.pleiarAuthRedirect = location.pathname;
        const login_url = getAuthURL();
        return <div className="authOverlay">
            <ExternalLink basicStyle={true} href="https://www.fagforbundet.no/"><img className="img-fluid branding" src="/brand.png" alt="Fagforbundet" /></ExternalLink>
            <div className="loginBox">
                Pleiar.no er en tjeneste levert av Fagforbundet til sine medlemmer.<br />
                Er du medlem bruker du bare mobiltelefonen din eller BankID
                for å <ExternalLink sameWindow={true} href={login_url}>logge inn</ExternalLink>.
                Ikke medlem? <ExternalLink sameWindow={true}
                    href="https://www.fagforbundet.no/medlemskap-og-fordeler/">Meld
                    deg inn</ExternalLink>!<br /><br />
                <ExternalLink sameWindow={true} href={login_url}><Button color="primary">Logg inn</Button></ExternalLink>{' '}
                <ExternalLink sameWindow={true} href="https://www.fagforbundet.no/medlemskap-og-fordeler/"><Button color="secondary">Bli medlem</Button></ExternalLink>
            </div>
        </div>;
    }
}
 
/**
 * Renders a block of text usable as an "inline" paywall
 */
class InlineAuthBlock extends React.Component<{|attemptedAccess: string|}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        window.localStorage.pleiarAuthRedirect = location.pathname;
        const login_url = AUTH_URL+'?return_to='+location.origin+'/auth&app_id='+AUTH_APPID;
        return <div className="authBlock">
            Tilgang til {this.props.attemptedAccess} er avgrenset til medlemmer
            av Fagforbundet. Hvis du er medlem kan du <ExternalLink sameWindow={true} href={login_url}>logge
            inn</ExternalLink>. Ellers er du hjertelig velkommen til å <ExternalLink
            href="https://www.fagforbundet.no/medlemskap-og-fordeler/">bli
            medlem</ExternalLink>
        </div>;
    }
}
 
/**
 * Props for RequiresAuth
 */
type RequiresAuthProps = {| children: React.Node |}
| {|
    children: React.Node,
    type: "article",
    title: string,
    image?: string,
    author?: string
|};
 
/**
 * This is a react wrapper around any component that requires the user to be
 * authenticated. It checks if the user has been authenticated. If they have,
 * it renders all the children directly. Otherwise it wraps the children in a
 * div, displays the auth overlay, and renders the children behind the overlay.
 */
class RequiresAuth extends React.Component<RequiresAuthProps>
{
    wrapperDiv: {| current: ?HTMLDivElement |};
    childrenDiv: {| current: ?HTMLDivElement |};
    observer: MutationObserver;
 
    constructor (props: RequiresAuthProps) // eslint-disable-line require-jsdoc
    {
        super(props);
        this.wrapperDiv = React.createRef();
        this.childrenDiv = React.createRef();
    }
 
    /**
    * Connect a MutationObserver to handle className changes when we mount
    */
    componentDidMount()
    {
        if(window.MutationObserver === undefined)
        {
            return;
        }
        const observer = new MutationObserver( (list) =>
        {
            for(const mutation of list)
            {
                Eif (mutation.type === 'attributes' && mutation.attributeName === "class")
                {
                    if(mutation.target === this.wrapperDiv.current && this.wrapperDiv.current != null && this.wrapperDiv.current.className !== "authn")
                    {
                        this.wrapperDiv.current.className = "authn";
                    }
                    else Eif(mutation.target === this.childrenDiv.current && this.childrenDiv.current != null && this.childrenDiv.current.className !== "requiresAuthentication auth-content")
                    {
                        this.childrenDiv.current.className = "requiresAuthentication auth-content";
                    }
                }
            }
        });
        this.observer = observer;
        if(this.wrapperDiv.current !== null && this.wrapperDiv.current !== undefined)
        {
            observer.observe(this.wrapperDiv.current, { attributes: true });
        }
        if(this.childrenDiv.current !== null && this.childrenDiv.current !== undefined)
        {
            observer.observe(this.childrenDiv.current, { attributes: true });
        }
    }
 
    /**
    * Disconnect our MutationObserver when we unmount
    */
    componentWillUnmount ()
    {
        Eif(this.observer !== undefined)
        {
            this.observer.disconnect();
        }
    }
 
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        let structured: React.Node;
        if(this.props.type && this.props.type === "article")
        {
            structured = <StructuredData key="StructuredData" walled={true} type="article" author={this.props.author} image={this.props.image} title={this.props.title} />;
        }
        else
        {
            structured = <StructuredData key="StructuredData" walled={true} type="auto" />;
        }
        if(auth.isAuthenticated())
        {
            return [
                <div key="auth-entry" className="auth-content">
                    {this.props.children}
                </div>,
                structured
            ];
        }
        else
        {
            return <div className="authn" ref={this.wrapperDiv}>
                <AuthOverlay />
                <div className="requiresAuthentication auth-content" ref={this.childrenDiv}>
                    {this.props.children}
                </div>
                {structured}
            </div>;
        }
    }
}
 
// Public exports
export { RequiresAuth, Authenticator, InlineAuthBlock, getAuthURL };
// Testing exports
export { AuthOverlay };