1
+ //
2
+ // Created by sajith on 6/28/22.
3
+ //
4
+
5
+
6
+ #include " servers/ReportSession.h"
7
+
8
+ #include < iostream>
9
+ #include < stdexcept>
10
+
11
+ #include " constants/Constants.h"
12
+ #include " types/User.h"
13
+
14
+ namespace
15
+ {
16
+ std::size_t read (tcp::socket &sock, char *buff, const std::size_t n)
17
+ {
18
+ boost::system::error_code error;
19
+ const auto readLength = sock.read_some (boost::asio::buffer (buff, n), error);
20
+ std::cout << " Received " << readLength << " bytes\n " ;
21
+
22
+ if (error == boost::asio::error::eof)
23
+ {
24
+ return 0 ;
25
+ }
26
+ else if (error)
27
+ {
28
+ throw boost::system::system_error{error};
29
+ }
30
+ return readLength;
31
+ }
32
+ }
33
+
34
+
35
+ namespace servers
36
+ {
37
+ ReportSession::ReportSession (tcp::socket sk, const auth::IAuthentication &aManager,
38
+ const parsers::ICredentialsParser &pser,
39
+ const services::ITaxServiceFactory &tSF) : sock{std::move (sk)}, authManager{aManager},
40
+ parser{pser}, taxServiceFactory{tSF}
41
+ {}
42
+
43
+ std::optional<types::User> ReportSession::loginUser ()
44
+ {
45
+ if (const auto length = read (sock, data, MAX_LENGTH))
46
+ {
47
+ const auto user = parser.parseCredentials ({data, length});
48
+ if (user && authManager.authenticate (user->login , user->password ))
49
+ {
50
+ return user;
51
+ }
52
+ }
53
+ return std::nullopt ;
54
+ }
55
+
56
+ void ReportSession::start () try
57
+ {
58
+ if (const auto user = loginUser ())
59
+ {
60
+ boost::asio::write (sock, boost::asio::buffer (constants::OK.data (), constants::OK.size ()));
61
+
62
+ for (auto taxService = taxServiceFactory.create (*user);;)
63
+ {
64
+ if (const auto length = read (sock, data, MAX_LENGTH))
65
+ {
66
+ const auto response = taxService->onReportRequest ({data, length});
67
+ boost::asio::write (sock, boost::asio::buffer (response.data (), response.size ()));
68
+ }
69
+ else
70
+ {
71
+ stop ();
72
+ }
73
+ }
74
+ }
75
+ else
76
+ {
77
+ boost::asio::write (sock, boost::asio::buffer (constants::NOK.data (), constants::NOK.size ()));
78
+ stop ();
79
+ std::cerr << __FILE__ << " Failed to login a user for tax reporting\n " ;
80
+ }
81
+ }catch (const std::exception &e)
82
+ {
83
+ std::cerr<<__FILE__<<' ' << __LINE__ <<' ' <<e.what ()<<' \n ' ;
84
+ }
85
+
86
+
87
+ void ReportSession::stop ()
88
+ {
89
+
90
+ }
91
+ }
0 commit comments