1 /*
2  * Copyright (c) 2015 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/shell/shell.h>
9 #include <zephyr/init.h>
10 
11 #define DEFAULT_PASSWORD "zephyr"
12 
login_init(void)13 static int login_init(void)
14 {
15 	printk("Shell Login Demo\nHint: password = %s\n", DEFAULT_PASSWORD);
16 	if (!CONFIG_SHELL_CMD_ROOT[0]) {
17 		shell_set_root_cmd("login");
18 	}
19 	return 0;
20 }
21 
check_passwd(char * passwd)22 static int check_passwd(char *passwd)
23 {
24 	/* example only -- not recommended for production use */
25 	return strcmp(passwd, DEFAULT_PASSWORD);
26 }
27 
cmd_login(const struct shell * sh,size_t argc,char ** argv)28 static int cmd_login(const struct shell *sh, size_t argc, char **argv)
29 {
30 	static uint32_t attempts;
31 
32 	if (check_passwd(argv[1]) != 0) {
33 		shell_error(sh, "Incorrect password!");
34 		attempts++;
35 		if (attempts > 3) {
36 			k_sleep(K_SECONDS(attempts));
37 		}
38 		return -EINVAL;
39 	}
40 
41 	/* clear history so password not visible there */
42 	z_shell_history_purge(sh->history);
43 	shell_obscure_set(sh, false);
44 	shell_set_root_cmd(NULL);
45 	shell_prompt_change(sh, "uart:~$ ");
46 	shell_print(sh, "Shell Login Demo\n");
47 	shell_print(sh, "Hit tab for help.\n");
48 	attempts = 0;
49 	return 0;
50 }
51 
cmd_logout(const struct shell * sh,size_t argc,char ** argv)52 static int cmd_logout(const struct shell *sh, size_t argc, char **argv)
53 {
54 	shell_set_root_cmd("login");
55 	shell_obscure_set(sh, true);
56 	shell_prompt_change(sh, "login: ");
57 	shell_print(sh, "\n");
58 	return 0;
59 }
60 
61 SHELL_CMD_ARG_REGISTER(login, NULL, "<password>", cmd_login, 2, 0);
62 
63 SHELL_CMD_REGISTER(logout, NULL, "Log out.", cmd_logout);
64 
65 SYS_INIT(login_init, APPLICATION, CONFIG_APPLICATION_INIT_PRIORITY);
66