Home > Enterprise >  how to initialize a boolean variable for every api call?
how to initialize a boolean variable for every api call?

Time:12-23

i have an api

public interface UserService{

@GetMapping("/get-user-data")
public Response getUserData();

}

i have my impl as below

public class UserServiceImpl implements UserService{

private boolean isAuthorized = false;

public Response getUserData(User user){
    //check if user is authorized
    isAuthorized = isUserAuthorized()?true:false;
    //perform other things based on above boolean
    return someResponse;
    }
}

i want this boolean "isAuthorized" must be set to false for every call to this api. whatever i have above isn't working, how to achieve this?

CodePudding user response:

Instead of keeping track of the state of the boolean variable, usually we perform some action based on the positive condition:

public Response getUserData(User user){
    if (isUserAuthorized()) {
        // actions that should happen only when authorized
    } else {
        // actions that should happen only when NOT authorized 
    }
}

But if you really want to keep track of that state, you can always set the variable to false at the end of the method call:

//check if user is authorized
isAuthorized = isUserAuthorized()?true:false;
//perform other things based on above boolean
isAuthorized = false;
return someResponse;

Note: that may cause issues related to concurrency, but if that doesn't concern you, no harm.

CodePudding user response:

if you want to call a business logic method for all api methods, you need to use a web HandlerInterceptor, by example:

@Component
public class AppInterceptor implements HandlerInterceptor {

    private static Logger logger = LoggerFactory.getLogger(AppInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        var authorized = UserIsAuthorizedDummy(); // <- you business logic here
        request.setAttribute("is_authorized", authorized);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {}

    private boolean UserIsAuthorizedDummy() {
        return true;
    }
}

And configure this interceptor with a WebMvcConfigurer implementation, by example:

@Configuration
public class AppConfig implements WebMvcConfigurer {
    @Autowired
    AppInterceptor appInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(appInterceptor);
    }
}

Then you can use it in you controller methods, and you will see and access the is_authorized atrribute from request object. example:

@GetMapping("/user")
    public LocalResponse getUser(HttpServletRequest request) {
        var response = new LocalResponse();
        // check AppInterceptor.preHandle() to see when "is_authorized" attribute is set
        response.setAuthorized((boolean) request.getAttribute("is_authorized"));

        if (response.isAuthorized()) {
            response.setUserId("1111");
        }

        return response;
    }

    @GetMapping("/profile")
    public LocalResponse getProfile(HttpServletRequest request) {
        var response = new LocalResponse();
        // check AppInterceptor.preHandle() to see when "is_authorized" attribute is set
        response.setAuthorized((boolean) request.getAttribute("is_authorized"));

        if (response.isAuthorized()) {
            response.setUserId("1111-22222");
        }

        return response;
    }

You can see a working example in the following repository: https://github.com/eriknyk/springboot-web-interceptor-demo/

  • Related