1 /* 2 * Copyright (C) 2019 The Dagger Authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package dagger.example.atm; 18 19 import dagger.example.atm.Database.Account; 20 import java.util.Optional; 21 import javax.inject.Inject; 22 23 /** Logs in a user, allowing them to interact with the ATM. */ 24 final class LoginCommand extends SingleArgCommand { 25 private final Outputter outputter; 26 private final Optional<Account> account; 27 private final UserCommandsRouter.Factory userCommandsFactory; 28 29 @Inject LoginCommand( Outputter outputter, Optional<Account> account, UserCommandsRouter.Factory userCommandsFactory)30 LoginCommand( 31 Outputter outputter, 32 Optional<Account> account, 33 UserCommandsRouter.Factory userCommandsFactory) { 34 this.outputter = outputter; 35 this.account = account; 36 this.userCommandsFactory = userCommandsFactory; 37 } 38 39 @Override handleArg(String username)40 public Result handleArg(String username) { 41 // If an Account binding exists, that means there is a user logged in. Don't allow a login 42 // command if we already have someone logged in! 43 if (account.isPresent()) { 44 String loggedInUser = account.get().username(); 45 outputter.output(loggedInUser + " is already logged in"); 46 if (!loggedInUser.equals(username)) { 47 outputter.output("run `logout` first before trying to log in another user"); 48 } 49 return Result.handled(); 50 } else { 51 UserCommandsRouter userCommands = userCommandsFactory.create(username); 52 return Result.enterNestedCommandSet(userCommands.router()); 53 } 54 } 55 } 56