Let's assume certain invention is patented in country A, but not in B (in the latter it should be considered novel and non-obvious). Can a random person (not the original inventor) apply for and be granted a patent in country B on that same invention (thus prohibiting the inventor to produce/sell it in B)?
Depends on the laws in Country B.
Different countries have different laws, and in some countries, it might be legal to patent other people's inventions from other countries. While First World/developed countries would likely try to prevent this, some Third World/developing countries have a much more permissive attitude towards patent law, and may well turn a blind eye to natives of that country stealing patents from foreigners.