-
+ {
+ api.loggedIn ?
+
+ : null
+ }
{item}
diff --git a/src/components/ForgotPassword.js b/src/components/ForgotPassword.js
new file mode 100644
index 0000000..c1a0131
--- /dev/null
+++ b/src/components/ForgotPassword.js
@@ -0,0 +1,63 @@
+/* Pi-hole: A black hole for Internet advertisements
+* (c) 2017 Pi-hole, LLC (https://pi-hole.net)
+* Network-wide ad blocking via your own hardware.
+*
+* Web Interface
+* Forgot Password Reminder
+*
+* This file is copyright under the latest version of the EUPL.
+* Please see LICENSE file for your rights under this license. */
+
+import React, { Component } from 'react';
+import PropTypes from 'prop-types';
+
+export default class ForgotPassword extends Component {
+ state = {
+ collapsed: true
+ };
+
+ /**
+ * Handle collapsing the body when clicked
+ */
+ onClick = () => {
+ this.setState({ collapsed: !this.state.collapsed });
+ };
+
+ /**
+ * @returns {Boolean|boolean} If the body should be expanded
+ */
+ isExpanded = () => this.props.error || !this.state.collapsed;
+
+ render() {
+ return (
+
+
+
+
+ Forgot password
+
+
+
+
+
+
+
+ After installing Pi-hole for the first time, a password is generated and displayed to the user.
+ The password cannot be retrieved later on, but it is possible to set a new password (or
+ explicitly disable the password by setting an empty password) using the command:
+
sudo pihole -a -p
+
+
+
+ );
+ }
+}
+
+ForgotPassword.propTypes = {
+ error: PropTypes.bool.isRequired
+};
\ No newline at end of file
diff --git a/src/components/Sidebar.js b/src/components/Sidebar.js
index c66a5d0..397d82f 100644
--- a/src/components/Sidebar.js
+++ b/src/components/Sidebar.js
@@ -14,44 +14,61 @@ import { NavLink } from 'react-router-dom'
import { Nav, NavItem } from 'reactstrap';
import logo from '../img/logo.svg';
import { mobileSidebarHide } from "./Header";
+import { api } from "../utils";
+import StatusBadge from "./StatusBadge";
const nav = {
items: [
{
name: 'Dashboard',
url: '/dashboard',
- icon: 'fa fa-dashboard'
+ icon: 'fa fa-dashboard',
+ auth: false
},
{
name: 'Query Log',
url: '/query-log',
- icon: 'fa fa-database'
+ icon: 'fa fa-database',
+ auth: true
},
{
name: 'Whitelist',
url: '/whitelist',
- icon: 'fa fa-check-circle-o'
+ icon: 'fa fa-check-circle-o',
+ auth: false
},
{
name: 'Blacklist',
icon: 'fa fa-ban',
+ auth: false,
children: [
{
name: 'Exact',
url: '/blacklist',
- icon: 'fa fa-ban'
+ icon: 'fa fa-ban',
+ auth: false
},
{
name: 'Wildcard',
url: '/wildlist',
- icon: 'fa fa-ban'
+ icon: 'fa fa-ban',
+ auth: false
}
]
},
{
name: 'Login',
url: '/login',
- icon: 'fa fa-user'
+ icon: 'fa fa-user',
+ auth: false,
+ authStrict: true
+ },
+ {
+ name: 'Logout',
+ url: '/logout',
+ icon: 'fa fa-user-times',
+ auth: true,
+ authStrict: true
}
]
};
@@ -82,7 +99,18 @@ const navDropdown = (item, key, props) => (
);
const navList = (items, props) =>
- items.map((item, index) => item.children ? navDropdown(item, index, props) : navItem(item, index, props));
+ items.map((item, index) => {
+ // Don't show an item if it requires auth and we're not logged in
+ if(item.auth && !api.loggedIn)
+ return null;
+
+ // Some items (login page) should only be shown when logged in or logged out, not both
+ if(item.authStrict && item.auth !== api.loggedIn)
+ return null;
+
+ // At this point it's ok to show the item
+ return item.children ? navDropdown(item, index, props) : navItem(item, index, props);
+ });
const Sidebar = props => {
return (
@@ -100,7 +128,7 @@ const Sidebar = props => {
@@ -46,3 +49,31 @@ export default props => (
);
+
+/**
+ * Create a route which requires authentication.
+ * If the user is unauthenticated, they will be redirected to the login page.
+ * If the user logs in at the redirected login page, they will go to their original destination.
+ *
+ * @param Component The component that the authenticated user will see
+ * @param rest The rest of the Route arguments
+ * @returns Route
+ */
+const AuthRoute = ({ component: Component, ...rest }) => (
+
+ api.loggedIn ? (
+
+ ) : (
+
+ )
+ }
+ />
+);
+
diff --git a/src/index.js b/src/index.js
index c2980c5..b8de48f 100644
--- a/src/index.js
+++ b/src/index.js
@@ -13,8 +13,14 @@ import ReactDOM from 'react-dom';
import { HashRouter, Route, Switch } from 'react-router-dom'
import 'ionicons/dist/css/ionicons.min.css';
import Full from './containers/Full'
+import { api } from "./utils";
import { setupI18n } from './i18n';
+// Before rendering anything, check if there is a session cookie.
+// Note: the user could have an old session, so the first API call
+// will set loggedIn to false if necessary
+api.loggedIn = document.cookie.includes("user_id=");
+
setupI18n();
ReactDOM.render(
diff --git a/src/routes.js b/src/routes.js
index a7a3c0a..b06e93a 100644
--- a/src/routes.js
+++ b/src/routes.js
@@ -14,5 +14,6 @@ export default {
'/whitelist': 'Whitelist',
'/blacklist': 'Blacklist (Exact)',
'/wildlist': 'Blacklist (Wildcard)',
- '/login': 'Login'
+ '/login': 'Login',
+ '/logout': 'Logout'
};
diff --git a/src/utils.js b/src/utils.js
index c7c07ec..1735aba 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -20,7 +20,7 @@ export const makeCancelable = (promise, { repeat = null, interval = 0 } = {}) =>
const handle = (resolve, reject, val, isError) => {
if(hasCanceled)
- reject({isCanceled: true});
+ reject({ isCanceled: true });
else {
if(isError)
reject(val);
@@ -54,6 +54,18 @@ export const ignoreCancel = err => {
};
export const api = {
+ loggedIn: false,
+ authenticate(key) {
+ return fetch(api.urlFor("auth"), {
+ headers: new Headers({ "X-Pi-hole-Authenticate": key }),
+ credentials: this.credentialType()
+ })
+ .then(api.convertJSON)
+ .then(api.checkForErrors);
+ },
+ logout() {
+ return api.delete("auth");
+ },
getSummary() {
return api.get("stats/summary");
},
@@ -105,8 +117,14 @@ export const api = {
removeWildlist(domain) {
return api.delete("dns/wildlist/" + domain);
},
+ getStatus() {
+ return api.get("dns/status")
+ },
get(url) {
- return fetch(api.urlFor(url))
+ return fetch(api.urlFor(url), {
+ credentials: this.credentialType()
+ })
+ .then(api.checkIfLoggedOut)
.then(api.convertJSON)
.then(api.checkForErrors);
},
@@ -114,16 +132,36 @@ export const api = {
return fetch(api.urlFor(url), {
method: "POST",
body: JSON.stringify(data),
- headers: new Headers({ "Content-Type": "application/json" })
+ headers: new Headers({ "Content-Type": "application/json" }),
+ credentials: this.credentialType()
})
+ .then(api.checkIfLoggedOut)
.then(api.convertJSON)
.then(api.checkForErrors);
},
delete(url) {
- return fetch(api.urlFor(url), { method: "DELETE" })
+ return fetch(api.urlFor(url), {
+ method: "DELETE",
+ credentials: this.credentialType()
+ })
+ .then(api.checkIfLoggedOut)
.then(api.convertJSON)
.then(api.checkForErrors);
},
+ /**
+ * If the user is logged in, check if the user's session has lapsed.
+ * If so, log them out and refresh the page.
+ */
+ checkIfLoggedOut(response) {
+ if(api.loggedIn && response.status === 401) {
+ // Clear the user's old session and refresh the page
+ document.cookie = 'user_id=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
+ window.location.reload();
+ return Promise.reject({ isCanceled: true })
+ }
+
+ return Promise.resolve(response);
+ },
async convertJSON(data) {
if(!data.ok)
return Promise.reject({ data, json: await data.json() });
@@ -145,5 +183,10 @@ export const api = {
apiLocation = "/admin/api";
return apiLocation + "/" + endpoint;
+ },
+ credentialType() {
+ // Development API requests use a different origin (pi.hole) since it is running off of the developer's machine.
+ // Therefore, allow credentials to be used across origins when in development mode.
+ return config.developmentMode ? "include" : "same-origin";
}
};
\ No newline at end of file
diff --git a/src/views/Dashboard.js b/src/views/Dashboard.js
index c75eba9..1b2ca6e 100644
--- a/src/views/Dashboard.js
+++ b/src/views/Dashboard.js
@@ -8,7 +8,7 @@
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
-import React from 'react';
+import React, { Fragment } from 'react';
import SummaryStats from '../components/SummaryStats';
import QueriesGraph from '../components/QueriesGraph';
import QueryTypesOverTime from '../components/QueryTypesOverTime';
@@ -16,19 +16,26 @@ import ForwardDestOverTime from '../components/ForwardDestOverTime';
import TopDomains from '../components/TopDomains';
import TopBlocked from '../components/TopBlocked';
import TopClients from '../components/TopClients';
+import { api } from "../utils";
export default () => (
-
-
-
-
-
-
-
-
-
+ {
+ api.loggedIn ?
+
+
+
+
+
+
+
+
+
+
+
+ : null
+ }
);
diff --git a/src/views/Login.js b/src/views/Login.js
index 2972b4d..d39d083 100644
--- a/src/views/Login.js
+++ b/src/views/Login.js
@@ -8,39 +8,77 @@
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
-import React, { Component } from 'react';
+import React, { Component, Fragment } from 'react';
+import { Redirect } from 'react-router-dom';
+import sha from 'sha.js';
+import { api } from "../utils";
import logo from '../img/logo.svg';
+import routes from "../routes";
+import ForgotPassword from "../components/ForgotPassword";
export default class Login extends Component {
state = {
password: '',
error: false,
- forgotPasswordCollapsed: true
+ cookiesEnabled: false
};
+ componentWillMount() {
+ // Check if cookies are enabled
+ if(navigator.cookieEnabled)
+ this.setState({ cookiesEnabled: true });
+ }
+
+ /**
+ * Called when the user types into the password box.
+ * If they clicked Enter, try to authenticate them.
+ * Otherwise update the password in the state.
+ *
+ * @param e the event
+ */
handlePasswordChange = e => {
- if(e.keyCode === 13) {
- this.onAuth();
- }
+ if(e.keyCode === 13)
+ this.authenticate();
else
this.setState({ password: e.target.value })
};
- onAuth = () => {
- this.setState({ password: '' });
+ /**
+ * Try to authenticate the user
+ */
+ authenticate = () => {
+ // Hash the password twice before sending to the API
+ let hashedPassword = sha("sha256").update(this.state.password).digest("hex");
+ hashedPassword = sha("sha256").update(hashedPassword).digest("hex");
- // TODO: Authenticate against server
- let auth = false;
+ // Clear the state
+ this.setState({ password: '', error: false });
- if(auth) {
+ // Send the password to the API to authenticate the user
+ api.authenticate(hashedPassword)
+ .then(data => {
+ // Verify status
+ if(data.status !== "success") {
+ console.log("Failed to log in:");
+ console.log(data);
+ return;
+ }
- }
- else {
- this.setState({ error: true });
- }
+ api.loggedIn = true;
+
+ // Redirect to the page the user was originally going to, or if that doesn't exist, go to home
+ const redirect = this.props.location.state.from || '/';
+ this.props.history.push(redirect);
+ })
+ // If there was an error, tell the user they used the wrong password
+ .catch(() => this.setState({ error: true }));
};
render() {
+ // If the user is already logged in, then go to the home page
+ if(api.loggedIn)
+ return ;
+
return (
Sign in to start your session
+ {
+ // If the user tried to go to a protected page and is not logged in,
+ // tell them they will be redirected once login is successful
+ this.props.location.state && this.props.location.state.from.pathname in routes ?
+ (
+
+
+ You will be transferred to the {routes[this.props.location.state.from.pathname]}
+
+ ) : null
+ }
+ {
+ // If cookies are not enabled (or detected), show a warning
+ !this.state.cookiesEnabled ?
+
+ Verify that cookies are allowed for {window.location.host}
+
+ : null
+ }
-
- Verify that cookies are allowed for {window.location.host}
-
- After installing Pi-hole for the first time, a password is generated and displayed to the user.
- The password cannot be retrieved later on, but it is possible to set a new password (or
- explicitly disable the password by setting an empty password) using the command:
-
sudo pihole -a -p
-
-
-
-
+
diff --git a/src/views/Logout.js b/src/views/Logout.js
new file mode 100644
index 0000000..90244b5
--- /dev/null
+++ b/src/views/Logout.js
@@ -0,0 +1,24 @@
+/* Pi-hole: A black hole for Internet advertisements
+* (c) 2017 Pi-hole, LLC (https://pi-hole.net)
+* Network-wide ad blocking via your own hardware.
+*
+* Web Interface
+* Logout the user
+*
+* This file is copyright under the latest version of the EUPL.
+* Please see LICENSE file for your rights under this license. */
+
+import React, { Component } from 'react';
+import { Redirect } from 'react-router-dom';
+import { api } from "../utils";
+
+export default class Logout extends Component {
+ componentWillMount() {
+ api.loggedIn = false;
+ api.logout();
+ }
+
+ render() {
+ return ;
+ }
+}